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.

1807 lines
61KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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. // Your project must contain an AppConfig.h file with your project-specific settings in it,
  18. // and your header search path must make it accessible to the module's files.
  19. #include "AppConfig.h"
  20. //==============================================================================
  21. #if JucePlugin_Build_VST3 && (__APPLE_CPP__ || __APPLE_CC__ || _WIN32 || _WIN64)
  22. #include "../../juce_audio_processors/format_types/juce_VST3Headers.h"
  23. #include "../utility/juce_CheckSettingMacros.h"
  24. #include "../utility/juce_IncludeModuleHeaders.h"
  25. #include "../utility/juce_WindowsHooks.h"
  26. #include "../../juce_audio_processors/format_types/juce_VST3Common.h"
  27. #ifndef JUCE_VST3_CAN_REPLACE_VST2
  28. #define JUCE_VST3_CAN_REPLACE_VST2 1
  29. #endif
  30. #if JUCE_VST3_CAN_REPLACE_VST2
  31. #if JUCE_MSVC
  32. #pragma warning (push)
  33. #pragma warning (disable: 4514 4996)
  34. #endif
  35. #include <pluginterfaces/vst2.x/vstfxstore.h>
  36. #if JUCE_MSVC
  37. #pragma warning (pop)
  38. #endif
  39. #endif
  40. #undef Point
  41. #undef Component
  42. namespace juce
  43. {
  44. using namespace Steinberg;
  45. //==============================================================================
  46. class JuceLibraryRefCount
  47. {
  48. public:
  49. JuceLibraryRefCount() { if ((getCount()++) == 0) initialiseJuce_GUI(); }
  50. ~JuceLibraryRefCount() { if ((--getCount()) == 0) shutdownJuce_GUI(); }
  51. private:
  52. int& getCount() noexcept
  53. {
  54. static int count = 0;
  55. return count;
  56. }
  57. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceLibraryRefCount)
  58. };
  59. //==============================================================================
  60. #if JUCE_MAC
  61. extern void initialiseMac();
  62. extern void* attachComponentToWindowRef (Component*, void* parent, bool isNSView);
  63. extern void detachComponentFromWindowRef (Component*, void* window, bool isNSView);
  64. extern void setNativeHostWindowSize (void* window, Component*, int newWidth, int newHeight, bool isNSView);
  65. #endif
  66. //==============================================================================
  67. class JuceAudioProcessor : public FUnknown
  68. {
  69. public:
  70. JuceAudioProcessor (AudioProcessor* source) noexcept
  71. : refCount (0), audioProcessor (source) {}
  72. virtual ~JuceAudioProcessor() {}
  73. AudioProcessor* get() const noexcept { return audioProcessor; }
  74. JUCE_DECLARE_VST3_COM_QUERY_METHODS
  75. JUCE_DECLARE_VST3_COM_REF_METHODS
  76. static const FUID iid;
  77. private:
  78. Atomic<int> refCount;
  79. ScopedPointer<AudioProcessor> audioProcessor;
  80. JuceAudioProcessor() JUCE_DELETED_FUNCTION;
  81. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAudioProcessor)
  82. };
  83. //==============================================================================
  84. class JuceVST3EditController : public Vst::EditController,
  85. public Vst::IMidiMapping,
  86. public AudioProcessorListener
  87. {
  88. public:
  89. JuceVST3EditController (Vst::IHostApplication* host)
  90. {
  91. if (host != nullptr)
  92. host->queryInterface (FUnknown::iid, (void**) &hostContext);
  93. }
  94. //==============================================================================
  95. static const FUID iid;
  96. //==============================================================================
  97. REFCOUNT_METHODS (ComponentBase)
  98. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  99. {
  100. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FObject)
  101. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3EditController)
  102. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController)
  103. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController2)
  104. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  105. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IMidiMapping)
  106. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IPluginBase, Vst::IEditController)
  107. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IDependent, Vst::IEditController)
  108. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IEditController)
  109. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  110. {
  111. audioProcessor->addRef();
  112. *obj = audioProcessor;
  113. return kResultOk;
  114. }
  115. *obj = nullptr;
  116. return kNoInterface;
  117. }
  118. //==============================================================================
  119. tresult PLUGIN_API initialize (FUnknown* context) override
  120. {
  121. if (hostContext != context)
  122. {
  123. if (hostContext != nullptr)
  124. hostContext->release();
  125. hostContext = context;
  126. if (hostContext != nullptr)
  127. hostContext->addRef();
  128. }
  129. return kResultTrue;
  130. }
  131. tresult PLUGIN_API terminate() override
  132. {
  133. if (AudioProcessor* const pluginInstance = getPluginInstance())
  134. pluginInstance->removeListener (this);
  135. audioProcessor = nullptr;
  136. return EditController::terminate();
  137. }
  138. //==============================================================================
  139. struct Param : public Vst::Parameter
  140. {
  141. Param (AudioProcessor& p, int index) : owner (p), paramIndex (index)
  142. {
  143. info.id = (Vst::ParamID) index;
  144. toString128 (info.title, p.getParameterName (index));
  145. toString128 (info.shortTitle, p.getParameterName (index, 8));
  146. toString128 (info.units, p.getParameterLabel (index));
  147. const int numSteps = p.getParameterNumSteps (index);
  148. info.stepCount = (Steinberg::int32) (numSteps > 0 && numSteps < 0x7fffffff ? numSteps - 1 : 0);
  149. info.defaultNormalizedValue = p.getParameterDefaultValue (index);
  150. info.unitId = Vst::kRootUnitId;
  151. info.flags = p.isParameterAutomatable (index) ? Vst::ParameterInfo::kCanAutomate : 0;
  152. }
  153. virtual ~Param() {}
  154. bool setNormalized (Vst::ParamValue v) override
  155. {
  156. v = jlimit (0.0, 1.0, v);
  157. if (v != valueNormalized)
  158. {
  159. valueNormalized = v;
  160. changed();
  161. return true;
  162. }
  163. return false;
  164. }
  165. void toString (Vst::ParamValue, Vst::String128 result) const override
  166. {
  167. toString128 (result, owner.getParameterText (paramIndex, 128));
  168. }
  169. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  170. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  171. private:
  172. AudioProcessor& owner;
  173. int paramIndex;
  174. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Param)
  175. };
  176. //==============================================================================
  177. void setAudioProcessor (JuceAudioProcessor* audioProc)
  178. {
  179. if (audioProcessor != audioProc)
  180. {
  181. audioProcessor = audioProc;
  182. setupParameters();
  183. }
  184. }
  185. tresult PLUGIN_API connect (IConnectionPoint* other) override
  186. {
  187. if (other != nullptr && audioProcessor == nullptr)
  188. {
  189. const tresult result = ComponentBase::connect (other);
  190. if (! audioProcessor.loadFrom (other))
  191. sendIntMessage ("JuceVST3EditController", (Steinberg::int64) (pointer_sized_int) this);
  192. else
  193. setupParameters();
  194. return result;
  195. }
  196. jassertfalse;
  197. return kResultFalse;
  198. }
  199. //==============================================================================
  200. tresult PLUGIN_API getMidiControllerAssignment (Steinberg::int32, Steinberg::int16,
  201. Vst::CtrlNumber,
  202. Vst::ParamID& id) override
  203. {
  204. //TODO
  205. id = 0;
  206. return kNotImplemented;
  207. }
  208. //==============================================================================
  209. IPlugView* PLUGIN_API createView (const char* name) override
  210. {
  211. if (AudioProcessor* const pluginInstance = getPluginInstance())
  212. {
  213. if (pluginInstance->hasEditor() && name != nullptr
  214. && strcmp (name, Vst::ViewType::kEditor) == 0)
  215. {
  216. return new JuceVST3Editor (*this, *pluginInstance);
  217. }
  218. }
  219. return nullptr;
  220. }
  221. //==============================================================================
  222. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit ((Steinberg::uint32) index); }
  223. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override { performEdit ((Steinberg::uint32) index, (double) newValue); }
  224. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit ((Steinberg::uint32) index); }
  225. void audioProcessorChanged (AudioProcessor*) override
  226. {
  227. if (componentHandler != nullptr)
  228. componentHandler->restartComponent (Vst::kLatencyChanged & Vst::kParamValuesChanged);
  229. }
  230. //==============================================================================
  231. AudioProcessor* getPluginInstance() const noexcept
  232. {
  233. if (audioProcessor != nullptr)
  234. return audioProcessor->get();
  235. return nullptr;
  236. }
  237. private:
  238. //==============================================================================
  239. ComSmartPtr<JuceAudioProcessor> audioProcessor;
  240. const JuceLibraryRefCount juceCount;
  241. //==============================================================================
  242. void setupParameters()
  243. {
  244. if (AudioProcessor* const pluginInstance = getPluginInstance())
  245. {
  246. pluginInstance->addListener (this);
  247. if (parameters.getParameterCount() <= 0)
  248. for (int i = 0; i < pluginInstance->getNumParameters(); ++i)
  249. parameters.addParameter (new Param (*pluginInstance, i));
  250. audioProcessorChanged (pluginInstance);
  251. }
  252. }
  253. void sendIntMessage (const char* idTag, const Steinberg::int64 value)
  254. {
  255. jassert (hostContext != nullptr);
  256. if (Vst::IMessage* message = allocateMessage())
  257. {
  258. const FReleaser releaser (message);
  259. message->setMessageID (idTag);
  260. message->getAttributes()->setInt (idTag, value);
  261. sendMessage (message);
  262. }
  263. }
  264. //==============================================================================
  265. class JuceVST3Editor : public Vst::EditorView
  266. {
  267. public:
  268. JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
  269. : Vst::EditorView (&ec, nullptr),
  270. owner (&ec), pluginInstance (p)
  271. {
  272. #if JUCE_MAC
  273. macHostWindow = nullptr;
  274. isNSView = false;
  275. #endif
  276. component = new ContentWrapperComponent (*this, p);
  277. }
  278. //==============================================================================
  279. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  280. {
  281. if (type != nullptr && pluginInstance.hasEditor())
  282. {
  283. #if JUCE_WINDOWS
  284. if (strcmp (type, kPlatformTypeHWND) == 0)
  285. #else
  286. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  287. #endif
  288. return kResultTrue;
  289. }
  290. return kResultFalse;
  291. }
  292. tresult PLUGIN_API attached (void* parent, FIDString type) override
  293. {
  294. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  295. return kResultFalse;
  296. #if JUCE_WINDOWS
  297. component->addToDesktop (0, parent);
  298. component->setOpaque (true);
  299. component->setVisible (true);
  300. #else
  301. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  302. macHostWindow = juce::attachComponentToWindowRef (component, parent, isNSView);
  303. #endif
  304. component->resizeHostWindow();
  305. systemWindow = parent;
  306. attachedToParent();
  307. return kResultTrue;
  308. }
  309. tresult PLUGIN_API removed() override
  310. {
  311. if (component != nullptr)
  312. {
  313. #if JUCE_WINDOWS
  314. component->removeFromDesktop();
  315. #else
  316. if (macHostWindow != nullptr)
  317. {
  318. juce::detachComponentFromWindowRef (component, macHostWindow, isNSView);
  319. macHostWindow = nullptr;
  320. }
  321. #endif
  322. component = nullptr;
  323. }
  324. return CPluginView::removed();
  325. }
  326. tresult PLUGIN_API onSize (ViewRect* newSize) override
  327. {
  328. if (newSize != nullptr)
  329. {
  330. rect = *newSize;
  331. if (component != nullptr)
  332. component->setSize (rect.getWidth(), rect.getHeight());
  333. return kResultTrue;
  334. }
  335. jassertfalse;
  336. return kResultFalse;
  337. }
  338. tresult PLUGIN_API getSize (ViewRect* size) override
  339. {
  340. if (size != nullptr && component != nullptr)
  341. {
  342. *size = ViewRect (0, 0, component->getWidth(), component->getHeight());
  343. return kResultTrue;
  344. }
  345. return kResultFalse;
  346. }
  347. tresult PLUGIN_API canResize() override { return kResultTrue; }
  348. tresult PLUGIN_API checkSizeConstraint (ViewRect* rect) override
  349. {
  350. if (rect != nullptr && component != nullptr)
  351. {
  352. rect->right = rect->left + component->getWidth();
  353. rect->bottom = rect->top + component->getHeight();
  354. return kResultTrue;
  355. }
  356. jassertfalse;
  357. return kResultFalse;
  358. }
  359. private:
  360. //==============================================================================
  361. class ContentWrapperComponent : public juce::Component
  362. {
  363. public:
  364. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  365. : owner (editor),
  366. pluginEditor (plugin.createEditorIfNeeded())
  367. {
  368. setOpaque (true);
  369. setBroughtToFrontOnMouseClick (true);
  370. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  371. jassert (pluginEditor != nullptr);
  372. if (pluginEditor != nullptr)
  373. {
  374. addAndMakeVisible (pluginEditor);
  375. setBounds (pluginEditor->getLocalBounds());
  376. resizeHostWindow();
  377. }
  378. }
  379. ~ContentWrapperComponent()
  380. {
  381. if (pluginEditor != nullptr)
  382. {
  383. PopupMenu::dismissAllActiveMenus();
  384. pluginEditor->getAudioProcessor()->editorBeingDeleted (pluginEditor);
  385. }
  386. }
  387. void paint (Graphics& g) override
  388. {
  389. g.fillAll (Colours::black);
  390. }
  391. void childBoundsChanged (Component*) override
  392. {
  393. resizeHostWindow();
  394. }
  395. void resized() override
  396. {
  397. if (pluginEditor != nullptr)
  398. pluginEditor->setBounds (getLocalBounds());
  399. }
  400. void resizeHostWindow()
  401. {
  402. if (pluginEditor != nullptr)
  403. {
  404. const int w = pluginEditor->getWidth();
  405. const int h = pluginEditor->getHeight();
  406. #if JUCE_WINDOWS
  407. setSize (w, h);
  408. #else
  409. if (owner.macHostWindow != nullptr)
  410. juce::setNativeHostWindowSize (owner.macHostWindow, this, w, h, owner.isNSView);
  411. #endif
  412. if (owner.plugFrame != nullptr)
  413. {
  414. ViewRect newSize (0, 0, w, h);
  415. owner.plugFrame->resizeView (&owner, &newSize);
  416. }
  417. }
  418. }
  419. private:
  420. JuceVST3Editor& owner;
  421. ScopedPointer<AudioProcessorEditor> pluginEditor;
  422. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  423. };
  424. //==============================================================================
  425. ComSmartPtr<JuceVST3EditController> owner;
  426. AudioProcessor& pluginInstance;
  427. ScopedPointer<ContentWrapperComponent> component;
  428. friend class ContentWrapperComponent;
  429. #if JUCE_MAC
  430. void* macHostWindow;
  431. bool isNSView;
  432. #endif
  433. #if JUCE_WINDOWS
  434. WindowsHooks hooks;
  435. #endif
  436. //==============================================================================
  437. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  438. };
  439. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  440. };
  441. //==============================================================================
  442. class JuceVST3Component : public Vst::IComponent,
  443. public Vst::IAudioProcessor,
  444. public Vst::IUnitInfo,
  445. public Vst::IConnectionPoint,
  446. public AudioPlayHead
  447. {
  448. public:
  449. JuceVST3Component (Vst::IHostApplication* h)
  450. : refCount (1),
  451. host (h),
  452. audioInputs (Vst::kAudio, Vst::kInput),
  453. audioOutputs (Vst::kAudio, Vst::kOutput),
  454. eventInputs (Vst::kEvent, Vst::kInput),
  455. eventOutputs (Vst::kEvent, Vst::kOutput)
  456. {
  457. pluginInstance = createPluginFilterOfType (AudioProcessor::wrapperType_VST3);
  458. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  459. zerostruct (processContext);
  460. processSetup.maxSamplesPerBlock = 1024;
  461. processSetup.processMode = Vst::kRealtime;
  462. processSetup.sampleRate = 44100.0;
  463. processSetup.symbolicSampleSize = Vst::kSample32;
  464. pluginInstance->setPlayHead (this);
  465. }
  466. ~JuceVST3Component()
  467. {
  468. if (pluginInstance != nullptr)
  469. if (pluginInstance->getPlayHead() == this)
  470. pluginInstance->setPlayHead (nullptr);
  471. audioInputs.removeAll();
  472. audioOutputs.removeAll();
  473. eventInputs.removeAll();
  474. eventOutputs.removeAll();
  475. }
  476. //==============================================================================
  477. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  478. //==============================================================================
  479. static const FUID iid;
  480. JUCE_DECLARE_VST3_COM_REF_METHODS
  481. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  482. {
  483. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  484. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  485. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  486. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  487. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  488. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  489. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  490. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  491. {
  492. comPluginInstance->addRef();
  493. *obj = comPluginInstance;
  494. return kResultOk;
  495. }
  496. *obj = nullptr;
  497. return kNoInterface;
  498. }
  499. //==============================================================================
  500. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  501. {
  502. if (host != hostContext)
  503. host.loadFrom (hostContext);
  504. #if JucePlugin_MaxNumInputChannels > 0
  505. addAudioBusTo (audioInputs, TRANS("Audio Input"),
  506. getArrangementForNumChannels (JucePlugin_MaxNumInputChannels));
  507. #endif
  508. #if JucePlugin_MaxNumOutputChannels > 0
  509. addAudioBusTo (audioOutputs, TRANS("Audio Output"),
  510. getArrangementForNumChannels (JucePlugin_MaxNumOutputChannels));
  511. #endif
  512. #if JucePlugin_WantsMidiInput
  513. addEventBusTo (eventInputs, TRANS("MIDI Input"));
  514. #endif
  515. #if JucePlugin_ProducesMidiOutput
  516. addEventBusTo (eventOutputs, TRANS("MIDI Output"));
  517. #endif
  518. processContext.sampleRate = processSetup.sampleRate;
  519. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  520. return kResultTrue;
  521. }
  522. tresult PLUGIN_API terminate() override
  523. {
  524. getPluginInstance().releaseResources();
  525. return kResultTrue;
  526. }
  527. //==============================================================================
  528. tresult PLUGIN_API connect (IConnectionPoint* other) override
  529. {
  530. if (other != nullptr && juceVST3EditController == nullptr)
  531. juceVST3EditController.loadFrom (other);
  532. return kResultTrue;
  533. }
  534. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  535. {
  536. juceVST3EditController = nullptr;
  537. return kResultTrue;
  538. }
  539. tresult PLUGIN_API notify (Vst::IMessage* message) override
  540. {
  541. if (message != nullptr && juceVST3EditController == nullptr)
  542. {
  543. Steinberg::int64 value = 0;
  544. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  545. {
  546. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  547. if (juceVST3EditController != nullptr)
  548. juceVST3EditController->setAudioProcessor (comPluginInstance);
  549. else
  550. jassertfalse;
  551. }
  552. }
  553. return kResultTrue;
  554. }
  555. //==============================================================================
  556. tresult PLUGIN_API getControllerClassId (TUID classID) override
  557. {
  558. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  559. return kResultTrue;
  560. }
  561. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  562. {
  563. if (Vst::BusList* const busList = getBusListFor (type, dir))
  564. return busList->total();
  565. return 0;
  566. }
  567. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  568. Steinberg::int32 index, Vst::BusInfo& info) override
  569. {
  570. if (Vst::BusList* const busList = getBusListFor (type, dir))
  571. {
  572. if (Vst::Bus* const bus = (Vst::Bus*) busList->at (index))
  573. {
  574. info.mediaType = type;
  575. info.direction = dir;
  576. if (bus->getInfo (info))
  577. return kResultTrue;
  578. }
  579. }
  580. zerostruct (info);
  581. return kResultFalse;
  582. }
  583. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir,
  584. Steinberg::int32 index, TBool state) override
  585. {
  586. if (Vst::BusList* const busList = getBusListFor (type, dir))
  587. {
  588. if (Vst::Bus* const bus = (Vst::Bus*) busList->at (index))
  589. {
  590. bus->setActive (state);
  591. return kResultTrue;
  592. }
  593. }
  594. jassertfalse;
  595. return kResultFalse;
  596. }
  597. tresult PLUGIN_API setActive (TBool state) override
  598. {
  599. if (state == kResultFalse)
  600. {
  601. getPluginInstance().releaseResources();
  602. }
  603. else
  604. {
  605. double sampleRate = getPluginInstance().getSampleRate();
  606. int bufferSize = getPluginInstance().getBlockSize();
  607. sampleRate = processSetup.sampleRate > 0.0
  608. ? processSetup.sampleRate
  609. : sampleRate;
  610. bufferSize = processSetup.maxSamplesPerBlock > 0
  611. ? (int) processSetup.maxSamplesPerBlock
  612. : bufferSize;
  613. channelList.clear();
  614. channelList.insertMultiple (0, nullptr, jmax (JucePlugin_MaxNumInputChannels, JucePlugin_MaxNumOutputChannels) + 1);
  615. preparePlugin (sampleRate, bufferSize);
  616. }
  617. return kResultOk;
  618. }
  619. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  620. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  621. #if JUCE_VST3_CAN_REPLACE_VST2
  622. void loadVST2VstWBlock (const char* data, int size)
  623. {
  624. const int headerLen = htonl (*(juce::int32*) (data + 4));
  625. const struct fxBank* bank = (const struct fxBank*) (data + (8 + headerLen));
  626. const int version = htonl (bank->version); (void) version;
  627. jassert ('VstW' == htonl (*(juce::int32*) data));
  628. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  629. jassert (cMagic == htonl (bank->chunkMagic));
  630. jassert (chunkBankMagic == htonl (bank->fxMagic));
  631. jassert (version == 1 || version == 2);
  632. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  633. pluginInstance->setStateInformation (bank->content.data.chunk,
  634. jmin ((int) (size - (bank->content.data.chunk - data)),
  635. (int) htonl (bank->content.data.size)));
  636. }
  637. bool loadVST3PresetFile (const char* data, int size)
  638. {
  639. if (size < 48)
  640. return false;
  641. // At offset 4 there's a little-endian version number which seems to typically be 1
  642. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  643. const int chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  644. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  645. const int entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  646. jassert (entryCount > 0);
  647. for (int i = 0; i < entryCount; ++i)
  648. {
  649. const int entryOffset = chunkListOffset + 8 + 20 * i;
  650. if (entryOffset + 20 > size)
  651. return false;
  652. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  653. {
  654. // "Comp" entries seem to contain the data.
  655. juce::uint64 chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  656. juce::uint64 chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  657. if (chunkOffset + chunkSize > size)
  658. {
  659. jassertfalse;
  660. return false;
  661. }
  662. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  663. }
  664. }
  665. return true;
  666. }
  667. bool loadVST2CompatibleState (const char* data, int size)
  668. {
  669. if (size < 4)
  670. return false;
  671. if (htonl (*(juce::int32*) data) == 'VstW')
  672. {
  673. loadVST2VstWBlock (data, size);
  674. return true;
  675. }
  676. if (memcmp (data, "VST3", 4) == 0)
  677. {
  678. // In Cubase 5, when loading VST3 .vstpreset files,
  679. // we get the whole content of the files to load.
  680. // In Cubase 7 we get just the contents within and
  681. // we go directly to the loadVST2VstW codepath instead.
  682. return loadVST3PresetFile (data, size);
  683. }
  684. return false;
  685. }
  686. #endif
  687. bool loadStateData (const void* data, int size)
  688. {
  689. #if JUCE_VST3_CAN_REPLACE_VST2
  690. return loadVST2CompatibleState ((const char*) data, size);
  691. #else
  692. pluginInstance->setStateInformation (data, size);
  693. return true;
  694. #endif
  695. }
  696. bool readFromMemoryStream (IBStream* state)
  697. {
  698. FUnknownPtr<MemoryStream> s (state);
  699. if (s != nullptr
  700. && s->getData() != nullptr
  701. && s->getSize() > 0
  702. && s->getSize() < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  703. {
  704. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  705. if (getHostType().isAdobeAudition())
  706. if (s->getSize() >= 5 && memcmp (s->getData(), "VC2!E", 5) == 0)
  707. return false;
  708. return loadStateData (s->getData(), (int) s->getSize());
  709. }
  710. return false;
  711. }
  712. bool readFromUnknownStream (IBStream* state)
  713. {
  714. MemoryOutputStream allData;
  715. {
  716. const size_t bytesPerBlock = 4096;
  717. HeapBlock<char> buffer (bytesPerBlock);
  718. for (;;)
  719. {
  720. Steinberg::int32 bytesRead = 0;
  721. if (state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead) == kResultTrue && bytesRead > 0)
  722. {
  723. allData.write (buffer, bytesRead);
  724. continue;
  725. }
  726. break;
  727. }
  728. }
  729. const size_t dataSize = allData.getDataSize();
  730. return dataSize > 0 && dataSize < 0x7fffffff
  731. && loadStateData (allData.getData(), (int) dataSize);
  732. }
  733. tresult PLUGIN_API setState (IBStream* state) override
  734. {
  735. if (state == nullptr)
  736. return kInvalidArgument;
  737. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  738. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  739. if (readFromMemoryStream (state) || readFromUnknownStream (state))
  740. return kResultTrue;
  741. return kResultFalse;
  742. }
  743. #if JUCE_VST3_CAN_REPLACE_VST2
  744. static tresult writeVST2Int (IBStream* state, int n)
  745. {
  746. juce::int32 t = (juce::int32) htonl (n);
  747. return state->write (&t, 4);
  748. }
  749. static tresult writeVST2Header (IBStream* state)
  750. {
  751. tresult status = writeVST2Int (state, 'VstW');
  752. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  753. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  754. if (status == kResultOk) status = writeVST2Int (state, 0); // bypass
  755. return status;
  756. }
  757. #endif
  758. tresult PLUGIN_API getState (IBStream* state) override
  759. {
  760. if (state == nullptr)
  761. return kInvalidArgument;
  762. juce::MemoryBlock mem;
  763. pluginInstance->getStateInformation (mem);
  764. #if JUCE_VST3_CAN_REPLACE_VST2
  765. tresult status = writeVST2Header (state);
  766. if (status != kResultOk)
  767. return status;
  768. const int bankBlockSize = 160;
  769. struct fxBank bank;
  770. zerostruct (bank);
  771. bank.chunkMagic = htonl (cMagic);
  772. bank.byteSize = htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  773. bank.fxMagic = htonl (chunkBankMagic);
  774. bank.version = htonl (2);
  775. bank.fxID = htonl (JucePlugin_VSTUniqueID);
  776. bank.fxVersion = htonl (JucePlugin_VersionCode);
  777. bank.content.data.size = htonl ((unsigned int) mem.getSize());
  778. status = state->write (&bank, bankBlockSize);
  779. if (status != kResultOk)
  780. return status;
  781. #endif
  782. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  783. }
  784. //==============================================================================
  785. Steinberg::int32 PLUGIN_API getUnitCount() override
  786. {
  787. return 1;
  788. }
  789. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  790. {
  791. if (unitIndex == 0)
  792. {
  793. info.id = Vst::kRootUnitId;
  794. info.parentUnitId = Vst::kNoParentUnitId;
  795. info.programListId = Vst::kNoProgramListId;
  796. toString128 (info.name, TRANS("Root Unit"));
  797. return kResultTrue;
  798. }
  799. zerostruct (info);
  800. return kResultFalse;
  801. }
  802. Steinberg::int32 PLUGIN_API getProgramListCount() override
  803. {
  804. if (getPluginInstance().getNumPrograms() > 0)
  805. return 1;
  806. return 0;
  807. }
  808. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  809. {
  810. if (listIndex == 0)
  811. {
  812. info.id = paramPreset;
  813. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  814. toString128 (info.name, TRANS("Factory Presets"));
  815. return kResultTrue;
  816. }
  817. jassertfalse;
  818. zerostruct (info);
  819. return kResultFalse;
  820. }
  821. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  822. {
  823. if (listId == paramPreset
  824. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  825. {
  826. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  827. return kResultTrue;
  828. }
  829. jassertfalse;
  830. toString128 (name, juce::String());
  831. return kResultFalse;
  832. }
  833. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  834. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  835. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  836. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  837. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  838. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  839. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection,
  840. Steinberg::int32, Steinberg::int32,
  841. Vst::UnitID& unitId) override
  842. {
  843. zerostruct (unitId);
  844. return kNotImplemented;
  845. }
  846. //==============================================================================
  847. bool getCurrentPosition (CurrentPositionInfo& info) override
  848. {
  849. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  850. info.timeInSeconds = processContext.projectTimeMusic;
  851. info.bpm = jmax (1.0, processContext.tempo);
  852. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  853. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  854. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  855. info.ppqPosition = processContext.projectTimeMusic;
  856. info.ppqLoopStart = processContext.cycleStartMusic;
  857. info.ppqLoopEnd = processContext.cycleEndMusic;
  858. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  859. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  860. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  861. info.editOriginTime = 0.0;
  862. info.frameRate = AudioPlayHead::fpsUnknown;
  863. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  864. {
  865. switch (processContext.frameRate.framesPerSecond)
  866. {
  867. case 24: info.frameRate = AudioPlayHead::fps24; break;
  868. case 25: info.frameRate = AudioPlayHead::fps25; break;
  869. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  870. case 30:
  871. {
  872. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  873. info.frameRate = AudioPlayHead::fps30drop;
  874. else
  875. info.frameRate = AudioPlayHead::fps30;
  876. }
  877. break;
  878. default: break;
  879. }
  880. }
  881. return true;
  882. }
  883. //==============================================================================
  884. static tresult setBusArrangementFor (Vst::BusList& list,
  885. Vst::SpeakerArrangement* arrangement,
  886. Steinberg::int32 numBusses)
  887. {
  888. if (arrangement != nullptr && numBusses == 1) //Should only be 1 bus per BusList
  889. {
  890. Steinberg::int32 counter = 0;
  891. FOREACH_CAST (IPtr<Vst::Bus>, Vst::AudioBus, bus, list)
  892. if (counter < numBusses)
  893. bus->setArrangement (arrangement[counter]);
  894. counter++;
  895. ENDFOR
  896. return kResultTrue;
  897. }
  898. return kResultFalse;
  899. }
  900. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  901. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  902. {
  903. #if JucePlugin_MaxNumInputChannels > 0
  904. if (setBusArrangementFor (audioInputs, inputs, numIns) != kResultTrue)
  905. return kResultFalse;
  906. #else
  907. if (numIns != 0)
  908. return kResultFalse;
  909. #endif
  910. #if JucePlugin_MaxNumOutputChannels > 0
  911. if (setBusArrangementFor (audioOutputs, outputs, numOuts) != kResultTrue)
  912. return kResultFalse;
  913. #else
  914. if (numOuts != 0)
  915. return kResultFalse;
  916. #endif
  917. preparePlugin (getPluginInstance().getSampleRate(),
  918. getPluginInstance().getBlockSize());
  919. return kResultTrue;
  920. }
  921. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  922. {
  923. if (Vst::BusList* const busList = getBusListFor (Vst::kAudio, dir))
  924. {
  925. if (Vst::AudioBus* const audioBus = FCast<Vst::AudioBus> (busList->at (index)))
  926. {
  927. arr = audioBus->getArrangement();
  928. return kResultTrue;
  929. }
  930. }
  931. return kResultFalse;
  932. }
  933. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  934. {
  935. return symbolicSampleSize == Vst::kSample32 ? kResultTrue : kResultFalse;
  936. }
  937. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  938. {
  939. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  940. }
  941. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  942. {
  943. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  944. return kResultFalse;
  945. processSetup = newSetup;
  946. processContext.sampleRate = processSetup.sampleRate;
  947. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  948. return kResultTrue;
  949. }
  950. tresult PLUGIN_API setProcessing (TBool state) override
  951. {
  952. if (state == kResultFalse)
  953. getPluginInstance().reset();
  954. return kResultTrue;
  955. }
  956. Steinberg::uint32 PLUGIN_API getTailSamples() override
  957. {
  958. const double tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  959. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  960. return Vst::kNoTail;
  961. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  962. }
  963. //==============================================================================
  964. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  965. {
  966. jassert (pluginInstance != nullptr);
  967. const Steinberg::int32 numParamsChanged = paramChanges.getParameterCount();
  968. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  969. {
  970. if (Vst::IParamValueQueue* paramQueue = paramChanges.getParameterData (i))
  971. {
  972. const Steinberg::int32 numPoints = paramQueue->getPointCount();
  973. Steinberg::int32 offsetSamples;
  974. double value = 0.0;
  975. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  976. {
  977. const int id = (int) paramQueue->getParameterId();
  978. jassert (isPositiveAndBelow (id, pluginInstance->getNumParameters()));
  979. pluginInstance->setParameter (id, (float) value);
  980. }
  981. }
  982. }
  983. }
  984. tresult PLUGIN_API process (Vst::ProcessData& data) override
  985. {
  986. if (pluginInstance == nullptr)
  987. return kResultFalse;
  988. if (data.processContext != nullptr)
  989. processContext = *data.processContext;
  990. else
  991. zerostruct (processContext);
  992. midiBuffer.clear();
  993. #if JucePlugin_WantsMidiInput
  994. if (data.inputEvents != nullptr)
  995. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  996. #endif
  997. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  998. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  999. #endif
  1000. const int numInputChans = data.inputs != nullptr ? (int) data.inputs[0].numChannels : 0;
  1001. const int numOutputChans = data.outputs != nullptr ? (int) data.outputs[0].numChannels : 0;
  1002. int totalChans = 0;
  1003. while (totalChans < numInputChans)
  1004. {
  1005. channelList.set (totalChans, data.inputs[0].channelBuffers32[totalChans]);
  1006. ++totalChans;
  1007. }
  1008. while (totalChans < numOutputChans)
  1009. {
  1010. channelList.set (totalChans, data.outputs[0].channelBuffers32[totalChans]);
  1011. ++totalChans;
  1012. }
  1013. AudioSampleBuffer buffer (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1014. {
  1015. const ScopedLock sl (pluginInstance->getCallbackLock());
  1016. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1017. if (data.inputParameterChanges != nullptr)
  1018. processParameterChanges (*data.inputParameterChanges);
  1019. if (pluginInstance->isSuspended())
  1020. buffer.clear();
  1021. else
  1022. pluginInstance->processBlock (buffer, midiBuffer);
  1023. }
  1024. for (int i = 0; i < numOutputChans; ++i)
  1025. FloatVectorOperations::copy (data.outputs[0].channelBuffers32[i], buffer.getReadPointer (i), (int) data.numSamples);
  1026. // clear extra busses..
  1027. if (data.outputs != nullptr)
  1028. for (int i = 1; i < data.numOutputs; ++i)
  1029. for (int f = 0; f < data.outputs[i].numChannels; ++f)
  1030. FloatVectorOperations::clear (data.outputs[i].channelBuffers32[f], (int) data.numSamples);
  1031. #if JucePlugin_ProducesMidiOutput
  1032. if (data.outputEvents != nullptr)
  1033. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1034. #elif JUCE_DEBUG
  1035. /* This assertion is caused when you've added some events to the
  1036. midiMessages array in your processBlock() method, which usually means
  1037. that you're trying to send them somewhere. But in this case they're
  1038. getting thrown away.
  1039. If your plugin does want to send MIDI messages, you'll need to set
  1040. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1041. JucePluginCharacteristics.h file.
  1042. If you don't want to produce any MIDI output, then you should clear the
  1043. midiMessages array at the end of your processBlock() method, to
  1044. indicate that you don't want any of the events to be passed through
  1045. to the output.
  1046. */
  1047. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1048. #endif
  1049. return kResultTrue;
  1050. }
  1051. private:
  1052. //==============================================================================
  1053. Atomic<int> refCount;
  1054. AudioProcessor* pluginInstance;
  1055. ComSmartPtr<Vst::IHostApplication> host;
  1056. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1057. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1058. /**
  1059. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1060. this object needs to be copied on every call to process() to be up-to-date...
  1061. */
  1062. Vst::ProcessContext processContext;
  1063. Vst::ProcessSetup processSetup;
  1064. Vst::BusList audioInputs, audioOutputs, eventInputs, eventOutputs;
  1065. MidiBuffer midiBuffer;
  1066. Array<float*> channelList;
  1067. const JuceLibraryRefCount juceCount;
  1068. //==============================================================================
  1069. void addBusTo (Vst::BusList& busList, Vst::Bus* newBus)
  1070. {
  1071. busList.append (IPtr<Vst::Bus> (newBus, false));
  1072. }
  1073. void addAudioBusTo (Vst::BusList& busList, const juce::String& name, Vst::SpeakerArrangement arr)
  1074. {
  1075. addBusTo (busList, new Vst::AudioBus (toString (name), Vst::kMain, Vst::BusInfo::kDefaultActive, arr));
  1076. }
  1077. void addEventBusTo (Vst::BusList& busList, const juce::String& name)
  1078. {
  1079. addBusTo (busList, new Vst::EventBus (toString (name), 16, Vst::kMain, Vst::BusInfo::kDefaultActive));
  1080. }
  1081. Vst::BusList* getBusListFor (Vst::MediaType type, Vst::BusDirection dir)
  1082. {
  1083. if (type == Vst::kAudio) return dir == Vst::kInput ? &audioInputs : &audioOutputs;
  1084. if (type == Vst::kEvent) return dir == Vst::kInput ? &eventInputs : &eventOutputs;
  1085. return nullptr;
  1086. }
  1087. //==============================================================================
  1088. enum InternalParameters
  1089. {
  1090. paramPreset = 'prst'
  1091. };
  1092. void preparePlugin (double sampleRate, int bufferSize)
  1093. {
  1094. Vst::BusInfo inputBusInfo, outputBusInfo;
  1095. audioInputs.first()->getInfo (inputBusInfo);
  1096. audioOutputs.first()->getInfo (outputBusInfo);
  1097. getPluginInstance().setPlayConfigDetails (inputBusInfo.channelCount,
  1098. outputBusInfo.channelCount,
  1099. sampleRate, bufferSize);
  1100. getPluginInstance().prepareToPlay (sampleRate, bufferSize);
  1101. }
  1102. //==============================================================================
  1103. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1104. };
  1105. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  1106. Steinberg::FUID getJuceVST3ComponentIID();
  1107. Steinberg::FUID getJuceVST3ComponentIID() { return JuceVST3Component::iid; }
  1108. #endif
  1109. //==============================================================================
  1110. #if JUCE_MSVC
  1111. #pragma warning (push, 0)
  1112. #pragma warning (disable: 4310)
  1113. #elif JUCE_CLANG
  1114. #pragma clang diagnostic push
  1115. #pragma clang diagnostic ignored "-w"
  1116. #endif
  1117. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1118. DEF_CLASS_IID (JuceAudioProcessor)
  1119. #if JUCE_VST3_CAN_REPLACE_VST2
  1120. // NB: Nasty old-fashioned code in here because it's copied from the Steinberg example code.
  1121. static FUID getFUIDForVST2ID (bool forControllerUID)
  1122. {
  1123. char uidString[33];
  1124. const int vstfxid = (('V' << 16) | ('S' << 8) | (forControllerUID ? 'E' : 'T'));
  1125. char vstfxidStr[7] = { 0 };
  1126. sprintf (vstfxidStr, "%06X", vstfxid);
  1127. strcpy (uidString, vstfxidStr);
  1128. char uidStr[9] = { 0 };
  1129. sprintf (uidStr, "%08X", JucePlugin_VSTUniqueID);
  1130. strcat (uidString, uidStr);
  1131. char nameidStr[3] = { 0 };
  1132. const size_t len = strlen (JucePlugin_Name);
  1133. for (size_t i = 0; i <= 8; ++i)
  1134. {
  1135. juce::uint8 c = i < len ? JucePlugin_Name[i] : 0;
  1136. if (c >= 'A' && c <= 'Z')
  1137. c += 'a' - 'A';
  1138. sprintf (nameidStr, "%02X", c);
  1139. strcat (uidString, nameidStr);
  1140. }
  1141. FUID newOne;
  1142. newOne.fromString (uidString);
  1143. return newOne;
  1144. }
  1145. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1146. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1147. #else
  1148. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1149. DEF_CLASS_IID (JuceVST3EditController)
  1150. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1151. DEF_CLASS_IID (JuceVST3Component)
  1152. #endif
  1153. #if JUCE_MSVC
  1154. #pragma warning (pop)
  1155. #elif JUCE_CLANG
  1156. #pragma clang diagnostic pop
  1157. #endif
  1158. //==============================================================================
  1159. bool initModule()
  1160. {
  1161. #if JUCE_MAC
  1162. initialiseMac();
  1163. #endif
  1164. return true;
  1165. }
  1166. bool shutdownModule()
  1167. {
  1168. return true;
  1169. }
  1170. #undef JUCE_EXPORTED_FUNCTION
  1171. #if JUCE_WINDOWS
  1172. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1173. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1174. #define JUCE_EXPORTED_FUNCTION
  1175. #else
  1176. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1177. CFBundleRef globalBundleInstance = nullptr;
  1178. juce::uint32 numBundleRefs = 0;
  1179. juce::Array<CFBundleRef> bundleRefs;
  1180. enum { MaxPathLength = 2048 };
  1181. char modulePath[MaxPathLength] = { 0 };
  1182. void* moduleHandle = nullptr;
  1183. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1184. {
  1185. if (ref != nullptr)
  1186. {
  1187. ++numBundleRefs;
  1188. CFRetain (ref);
  1189. bundleRefs.add (ref);
  1190. if (moduleHandle == nullptr)
  1191. {
  1192. globalBundleInstance = ref;
  1193. moduleHandle = ref;
  1194. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1195. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1196. CFRelease (tempURL);
  1197. }
  1198. }
  1199. return initModule();
  1200. }
  1201. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1202. {
  1203. if (shutdownModule())
  1204. {
  1205. if (--numBundleRefs == 0)
  1206. {
  1207. for (int i = 0; i < bundleRefs.size(); ++i)
  1208. CFRelease (bundleRefs.getUnchecked (i));
  1209. bundleRefs.clear();
  1210. }
  1211. return true;
  1212. }
  1213. return false;
  1214. }
  1215. #endif
  1216. //==============================================================================
  1217. /** This typedef represents VST3's createInstance() function signature */
  1218. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1219. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1220. {
  1221. return (Vst::IAudioProcessor*) new JuceVST3Component (host);
  1222. }
  1223. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1224. {
  1225. return (Vst::IEditController*) new JuceVST3EditController (host);
  1226. }
  1227. //==============================================================================
  1228. class JucePluginFactory;
  1229. static JucePluginFactory* globalFactory = nullptr;
  1230. //==============================================================================
  1231. class JucePluginFactory : public IPluginFactory3
  1232. {
  1233. public:
  1234. JucePluginFactory()
  1235. : refCount (1),
  1236. factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1237. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1238. {
  1239. }
  1240. virtual ~JucePluginFactory()
  1241. {
  1242. if (globalFactory == this)
  1243. globalFactory = nullptr;
  1244. }
  1245. //==============================================================================
  1246. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1247. {
  1248. if (createFunction == nullptr)
  1249. {
  1250. jassertfalse;
  1251. return false;
  1252. }
  1253. ClassEntry* entry = classes.add (new ClassEntry (info, createFunction));
  1254. entry->infoW.fromAscii (info);
  1255. return true;
  1256. }
  1257. bool isClassRegistered (const FUID& cid) const
  1258. {
  1259. for (int i = 0; i < classes.size(); ++i)
  1260. if (classes.getUnchecked (i)->infoW.cid == cid)
  1261. return true;
  1262. return false;
  1263. }
  1264. //==============================================================================
  1265. JUCE_DECLARE_VST3_COM_REF_METHODS
  1266. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1267. {
  1268. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  1269. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  1270. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  1271. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  1272. jassertfalse; // Something new?
  1273. *obj = nullptr;
  1274. return kNotImplemented;
  1275. }
  1276. //==============================================================================
  1277. Steinberg::int32 PLUGIN_API countClasses() override
  1278. {
  1279. return (Steinberg::int32) classes.size();
  1280. }
  1281. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1282. {
  1283. if (info == nullptr)
  1284. return kInvalidArgument;
  1285. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  1286. return kResultOk;
  1287. }
  1288. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  1289. {
  1290. return getPClassInfo<PClassInfo> (index, info);
  1291. }
  1292. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  1293. {
  1294. return getPClassInfo<PClassInfo2> (index, info);
  1295. }
  1296. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  1297. {
  1298. if (info != nullptr)
  1299. {
  1300. if (ClassEntry* entry = classes[(int) index])
  1301. {
  1302. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  1303. return kResultOk;
  1304. }
  1305. }
  1306. return kInvalidArgument;
  1307. }
  1308. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  1309. {
  1310. *obj = nullptr;
  1311. FUID sourceFuid = sourceIid;
  1312. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  1313. {
  1314. jassertfalse; // The host you're running in has severe implementation issues!
  1315. return kInvalidArgument;
  1316. }
  1317. TUID iidToQuery;
  1318. sourceFuid.toTUID (iidToQuery);
  1319. for (int i = 0; i < classes.size(); ++i)
  1320. {
  1321. const ClassEntry& entry = *classes.getUnchecked (i);
  1322. if (doUIDsMatch (entry.infoW.cid, cid))
  1323. {
  1324. if (FUnknown* const instance = entry.createFunction (host))
  1325. {
  1326. const FReleaser releaser (instance);
  1327. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  1328. return kResultOk;
  1329. }
  1330. break;
  1331. }
  1332. }
  1333. return kNoInterface;
  1334. }
  1335. tresult PLUGIN_API setHostContext (FUnknown* context) override
  1336. {
  1337. host.loadFrom (context);
  1338. if (host != nullptr)
  1339. {
  1340. Vst::String128 name;
  1341. host->getName (name);
  1342. return kResultTrue;
  1343. }
  1344. return kNotImplemented;
  1345. }
  1346. private:
  1347. //==============================================================================
  1348. const JuceLibraryRefCount juceCount;
  1349. Atomic<int> refCount;
  1350. const PFactoryInfo factoryInfo;
  1351. ComSmartPtr<Vst::IHostApplication> host;
  1352. //==============================================================================
  1353. struct ClassEntry
  1354. {
  1355. ClassEntry() noexcept : createFunction (nullptr), isUnicode (false) {}
  1356. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  1357. : info2 (info), createFunction (fn), isUnicode (false) {}
  1358. PClassInfo2 info2;
  1359. PClassInfoW infoW;
  1360. CreateFunction createFunction;
  1361. bool isUnicode;
  1362. private:
  1363. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  1364. };
  1365. OwnedArray<ClassEntry> classes;
  1366. //==============================================================================
  1367. template<class PClassInfoType>
  1368. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  1369. {
  1370. if (info != nullptr)
  1371. {
  1372. zerostruct (*info);
  1373. if (ClassEntry* entry = classes[(int) index])
  1374. {
  1375. if (entry->isUnicode)
  1376. return kResultFalse;
  1377. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  1378. return kResultOk;
  1379. }
  1380. }
  1381. jassertfalse;
  1382. return kInvalidArgument;
  1383. }
  1384. //==============================================================================
  1385. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  1386. };
  1387. } // juce namespace
  1388. //==============================================================================
  1389. #ifndef JucePlugin_Vst3ComponentFlags
  1390. #if JucePlugin_IsSynth
  1391. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  1392. #else
  1393. #define JucePlugin_Vst3ComponentFlags 0
  1394. #endif
  1395. #endif
  1396. #ifndef JucePlugin_Vst3Category
  1397. #if JucePlugin_IsSynth
  1398. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  1399. #else
  1400. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  1401. #endif
  1402. #endif
  1403. //==============================================================================
  1404. // The VST3 plugin entry point.
  1405. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  1406. {
  1407. #if JUCE_WINDOWS
  1408. // Cunning trick to force this function to be exported. Life's too short to
  1409. // faff around creating .def files for this kind of thing.
  1410. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  1411. #endif
  1412. if (globalFactory == nullptr)
  1413. {
  1414. globalFactory = new JucePluginFactory();
  1415. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  1416. PClassInfo::kManyInstances,
  1417. kVstAudioEffectClass,
  1418. JucePlugin_Name,
  1419. JucePlugin_Vst3ComponentFlags,
  1420. JucePlugin_Vst3Category,
  1421. JucePlugin_Manufacturer,
  1422. JucePlugin_VersionString,
  1423. kVstVersionString);
  1424. globalFactory->registerClass (componentClass, createComponentInstance);
  1425. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  1426. PClassInfo::kManyInstances,
  1427. kVstComponentControllerClass,
  1428. JucePlugin_Name,
  1429. JucePlugin_Vst3ComponentFlags,
  1430. JucePlugin_Vst3Category,
  1431. JucePlugin_Manufacturer,
  1432. JucePlugin_VersionString,
  1433. kVstVersionString);
  1434. globalFactory->registerClass (controllerClass, createControllerInstance);
  1435. }
  1436. else
  1437. {
  1438. globalFactory->addRef();
  1439. }
  1440. return dynamic_cast<IPluginFactory*> (globalFactory);
  1441. }
  1442. #endif //JucePlugin_Build_VST3