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.

1811 lines
62KB

  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. const Steinberg::tresult status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  722. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  723. break;
  724. allData.write (buffer, bytesRead);
  725. }
  726. }
  727. const size_t dataSize = allData.getDataSize();
  728. return dataSize > 0 && dataSize < 0x7fffffff
  729. && loadStateData (allData.getData(), (int) dataSize);
  730. }
  731. tresult PLUGIN_API setState (IBStream* state) override
  732. {
  733. if (state == nullptr)
  734. return kInvalidArgument;
  735. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  736. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  737. if (readFromMemoryStream (state) || readFromUnknownStream (state))
  738. return kResultTrue;
  739. return kResultFalse;
  740. }
  741. #if JUCE_VST3_CAN_REPLACE_VST2
  742. static tresult writeVST2Int (IBStream* state, int n)
  743. {
  744. juce::int32 t = (juce::int32) htonl (n);
  745. return state->write (&t, 4);
  746. }
  747. static tresult writeVST2Header (IBStream* state)
  748. {
  749. tresult status = writeVST2Int (state, 'VstW');
  750. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  751. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  752. if (status == kResultOk) status = writeVST2Int (state, 0); // bypass
  753. return status;
  754. }
  755. #endif
  756. tresult PLUGIN_API getState (IBStream* state) override
  757. {
  758. if (state == nullptr)
  759. return kInvalidArgument;
  760. juce::MemoryBlock mem;
  761. pluginInstance->getStateInformation (mem);
  762. #if JUCE_VST3_CAN_REPLACE_VST2
  763. tresult status = writeVST2Header (state);
  764. if (status != kResultOk)
  765. return status;
  766. const int bankBlockSize = 160;
  767. struct fxBank bank;
  768. zerostruct (bank);
  769. bank.chunkMagic = htonl (cMagic);
  770. bank.byteSize = htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  771. bank.fxMagic = htonl (chunkBankMagic);
  772. bank.version = htonl (2);
  773. bank.fxID = htonl (JucePlugin_VSTUniqueID);
  774. bank.fxVersion = htonl (JucePlugin_VersionCode);
  775. bank.content.data.size = htonl ((unsigned int) mem.getSize());
  776. status = state->write (&bank, bankBlockSize);
  777. if (status != kResultOk)
  778. return status;
  779. #endif
  780. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  781. }
  782. //==============================================================================
  783. Steinberg::int32 PLUGIN_API getUnitCount() override
  784. {
  785. return 1;
  786. }
  787. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  788. {
  789. if (unitIndex == 0)
  790. {
  791. info.id = Vst::kRootUnitId;
  792. info.parentUnitId = Vst::kNoParentUnitId;
  793. info.programListId = Vst::kNoProgramListId;
  794. toString128 (info.name, TRANS("Root Unit"));
  795. return kResultTrue;
  796. }
  797. zerostruct (info);
  798. return kResultFalse;
  799. }
  800. Steinberg::int32 PLUGIN_API getProgramListCount() override
  801. {
  802. if (getPluginInstance().getNumPrograms() > 0)
  803. return 1;
  804. return 0;
  805. }
  806. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  807. {
  808. if (listIndex == 0)
  809. {
  810. info.id = paramPreset;
  811. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  812. toString128 (info.name, TRANS("Factory Presets"));
  813. return kResultTrue;
  814. }
  815. jassertfalse;
  816. zerostruct (info);
  817. return kResultFalse;
  818. }
  819. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  820. {
  821. if (listId == paramPreset
  822. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  823. {
  824. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  825. return kResultTrue;
  826. }
  827. jassertfalse;
  828. toString128 (name, juce::String());
  829. return kResultFalse;
  830. }
  831. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  832. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  833. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  834. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  835. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  836. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  837. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection,
  838. Steinberg::int32, Steinberg::int32,
  839. Vst::UnitID& unitId) override
  840. {
  841. zerostruct (unitId);
  842. return kNotImplemented;
  843. }
  844. //==============================================================================
  845. bool getCurrentPosition (CurrentPositionInfo& info) override
  846. {
  847. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  848. info.timeInSeconds = processContext.projectTimeMusic;
  849. info.bpm = jmax (1.0, processContext.tempo);
  850. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  851. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  852. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  853. info.ppqPosition = processContext.projectTimeMusic;
  854. info.ppqLoopStart = processContext.cycleStartMusic;
  855. info.ppqLoopEnd = processContext.cycleEndMusic;
  856. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  857. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  858. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  859. info.editOriginTime = 0.0;
  860. info.frameRate = AudioPlayHead::fpsUnknown;
  861. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  862. {
  863. switch (processContext.frameRate.framesPerSecond)
  864. {
  865. case 24: info.frameRate = AudioPlayHead::fps24; break;
  866. case 25: info.frameRate = AudioPlayHead::fps25; break;
  867. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  868. case 30:
  869. {
  870. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  871. info.frameRate = AudioPlayHead::fps30drop;
  872. else
  873. info.frameRate = AudioPlayHead::fps30;
  874. }
  875. break;
  876. default: break;
  877. }
  878. }
  879. return true;
  880. }
  881. //==============================================================================
  882. static tresult setBusArrangementFor (Vst::BusList& list,
  883. Vst::SpeakerArrangement* arrangement,
  884. Steinberg::int32 numBusses)
  885. {
  886. if (arrangement != nullptr && numBusses == 1) //Should only be 1 bus per BusList
  887. {
  888. Steinberg::int32 counter = 0;
  889. FOREACH_CAST (IPtr<Vst::Bus>, Vst::AudioBus, bus, list)
  890. if (counter < numBusses)
  891. bus->setArrangement (arrangement[counter]);
  892. counter++;
  893. ENDFOR
  894. return kResultTrue;
  895. }
  896. return kResultFalse;
  897. }
  898. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  899. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  900. {
  901. #if JucePlugin_MaxNumInputChannels > 0
  902. if (setBusArrangementFor (audioInputs, inputs, numIns) != kResultTrue)
  903. return kResultFalse;
  904. #else
  905. if (numIns != 0)
  906. return kResultFalse;
  907. #endif
  908. #if JucePlugin_MaxNumOutputChannels > 0
  909. if (setBusArrangementFor (audioOutputs, outputs, numOuts) != kResultTrue)
  910. return kResultFalse;
  911. #else
  912. if (numOuts != 0)
  913. return kResultFalse;
  914. #endif
  915. preparePlugin (getPluginInstance().getSampleRate(),
  916. getPluginInstance().getBlockSize());
  917. return kResultTrue;
  918. }
  919. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  920. {
  921. if (Vst::BusList* const busList = getBusListFor (Vst::kAudio, dir))
  922. {
  923. if (Vst::AudioBus* const audioBus = FCast<Vst::AudioBus> (busList->at (index)))
  924. {
  925. arr = audioBus->getArrangement();
  926. return kResultTrue;
  927. }
  928. }
  929. return kResultFalse;
  930. }
  931. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  932. {
  933. return symbolicSampleSize == Vst::kSample32 ? kResultTrue : kResultFalse;
  934. }
  935. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  936. {
  937. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  938. }
  939. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  940. {
  941. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  942. return kResultFalse;
  943. processSetup = newSetup;
  944. processContext.sampleRate = processSetup.sampleRate;
  945. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  946. return kResultTrue;
  947. }
  948. tresult PLUGIN_API setProcessing (TBool state) override
  949. {
  950. if (state == kResultFalse)
  951. getPluginInstance().reset();
  952. return kResultTrue;
  953. }
  954. Steinberg::uint32 PLUGIN_API getTailSamples() override
  955. {
  956. const double tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  957. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  958. return Vst::kNoTail;
  959. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  960. }
  961. //==============================================================================
  962. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  963. {
  964. jassert (pluginInstance != nullptr);
  965. const Steinberg::int32 numParamsChanged = paramChanges.getParameterCount();
  966. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  967. {
  968. if (Vst::IParamValueQueue* paramQueue = paramChanges.getParameterData (i))
  969. {
  970. const Steinberg::int32 numPoints = paramQueue->getPointCount();
  971. Steinberg::int32 offsetSamples;
  972. double value = 0.0;
  973. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  974. {
  975. const int id = (int) paramQueue->getParameterId();
  976. jassert (isPositiveAndBelow (id, pluginInstance->getNumParameters()));
  977. pluginInstance->setParameter (id, (float) value);
  978. }
  979. }
  980. }
  981. }
  982. tresult PLUGIN_API process (Vst::ProcessData& data) override
  983. {
  984. if (pluginInstance == nullptr)
  985. return kResultFalse;
  986. if (data.processContext != nullptr)
  987. processContext = *data.processContext;
  988. else
  989. zerostruct (processContext);
  990. midiBuffer.clear();
  991. #if JucePlugin_WantsMidiInput
  992. if (data.inputEvents != nullptr)
  993. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  994. #endif
  995. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  996. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  997. #endif
  998. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  999. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1000. int totalChans = 0;
  1001. while (totalChans < numInputChans)
  1002. {
  1003. channelList.set (totalChans, data.inputs[0].channelBuffers32[totalChans]);
  1004. ++totalChans;
  1005. }
  1006. while (totalChans < numOutputChans)
  1007. {
  1008. channelList.set (totalChans, data.outputs[0].channelBuffers32[totalChans]);
  1009. ++totalChans;
  1010. }
  1011. AudioSampleBuffer buffer;
  1012. if (totalChans != 0)
  1013. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1014. else if (getHostType().isWavelab()
  1015. && pluginInstance->getNumInputChannels() + pluginInstance->getNumOutputChannels() > 0)
  1016. return kResultFalse;
  1017. {
  1018. const ScopedLock sl (pluginInstance->getCallbackLock());
  1019. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1020. if (data.inputParameterChanges != nullptr)
  1021. processParameterChanges (*data.inputParameterChanges);
  1022. if (pluginInstance->isSuspended())
  1023. buffer.clear();
  1024. else
  1025. pluginInstance->processBlock (buffer, midiBuffer);
  1026. }
  1027. for (int i = 0; i < numOutputChans; ++i)
  1028. FloatVectorOperations::copy (data.outputs[0].channelBuffers32[i], buffer.getReadPointer (i), (int) data.numSamples);
  1029. // clear extra busses..
  1030. if (data.outputs != nullptr)
  1031. for (int i = 1; i < data.numOutputs; ++i)
  1032. for (int f = 0; f < data.outputs[i].numChannels; ++f)
  1033. FloatVectorOperations::clear (data.outputs[i].channelBuffers32[f], (int) data.numSamples);
  1034. #if JucePlugin_ProducesMidiOutput
  1035. if (data.outputEvents != nullptr)
  1036. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1037. #elif JUCE_DEBUG
  1038. /* This assertion is caused when you've added some events to the
  1039. midiMessages array in your processBlock() method, which usually means
  1040. that you're trying to send them somewhere. But in this case they're
  1041. getting thrown away.
  1042. If your plugin does want to send MIDI messages, you'll need to set
  1043. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1044. JucePluginCharacteristics.h file.
  1045. If you don't want to produce any MIDI output, then you should clear the
  1046. midiMessages array at the end of your processBlock() method, to
  1047. indicate that you don't want any of the events to be passed through
  1048. to the output.
  1049. */
  1050. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1051. #endif
  1052. return kResultTrue;
  1053. }
  1054. private:
  1055. //==============================================================================
  1056. Atomic<int> refCount;
  1057. AudioProcessor* pluginInstance;
  1058. ComSmartPtr<Vst::IHostApplication> host;
  1059. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1060. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1061. /**
  1062. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1063. this object needs to be copied on every call to process() to be up-to-date...
  1064. */
  1065. Vst::ProcessContext processContext;
  1066. Vst::ProcessSetup processSetup;
  1067. Vst::BusList audioInputs, audioOutputs, eventInputs, eventOutputs;
  1068. MidiBuffer midiBuffer;
  1069. Array<float*> channelList;
  1070. const JuceLibraryRefCount juceCount;
  1071. //==============================================================================
  1072. void addBusTo (Vst::BusList& busList, Vst::Bus* newBus)
  1073. {
  1074. busList.append (IPtr<Vst::Bus> (newBus, false));
  1075. }
  1076. void addAudioBusTo (Vst::BusList& busList, const juce::String& name, Vst::SpeakerArrangement arr)
  1077. {
  1078. addBusTo (busList, new Vst::AudioBus (toString (name), Vst::kMain, Vst::BusInfo::kDefaultActive, arr));
  1079. }
  1080. void addEventBusTo (Vst::BusList& busList, const juce::String& name)
  1081. {
  1082. addBusTo (busList, new Vst::EventBus (toString (name), 16, Vst::kMain, Vst::BusInfo::kDefaultActive));
  1083. }
  1084. Vst::BusList* getBusListFor (Vst::MediaType type, Vst::BusDirection dir)
  1085. {
  1086. if (type == Vst::kAudio) return dir == Vst::kInput ? &audioInputs : &audioOutputs;
  1087. if (type == Vst::kEvent) return dir == Vst::kInput ? &eventInputs : &eventOutputs;
  1088. return nullptr;
  1089. }
  1090. //==============================================================================
  1091. enum InternalParameters
  1092. {
  1093. paramPreset = 'prst'
  1094. };
  1095. void preparePlugin (double sampleRate, int bufferSize)
  1096. {
  1097. Vst::BusInfo inputBusInfo, outputBusInfo;
  1098. audioInputs.first()->getInfo (inputBusInfo);
  1099. audioOutputs.first()->getInfo (outputBusInfo);
  1100. getPluginInstance().setPlayConfigDetails (inputBusInfo.channelCount,
  1101. outputBusInfo.channelCount,
  1102. sampleRate, bufferSize);
  1103. getPluginInstance().prepareToPlay (sampleRate, bufferSize);
  1104. }
  1105. //==============================================================================
  1106. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1107. };
  1108. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  1109. Steinberg::FUID getJuceVST3ComponentIID();
  1110. Steinberg::FUID getJuceVST3ComponentIID() { return JuceVST3Component::iid; }
  1111. #endif
  1112. //==============================================================================
  1113. #if JUCE_MSVC
  1114. #pragma warning (push, 0)
  1115. #pragma warning (disable: 4310)
  1116. #elif JUCE_CLANG
  1117. #pragma clang diagnostic push
  1118. #pragma clang diagnostic ignored "-w"
  1119. #endif
  1120. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1121. DEF_CLASS_IID (JuceAudioProcessor)
  1122. #if JUCE_VST3_CAN_REPLACE_VST2
  1123. // NB: Nasty old-fashioned code in here because it's copied from the Steinberg example code.
  1124. static FUID getFUIDForVST2ID (bool forControllerUID)
  1125. {
  1126. char uidString[33];
  1127. const int vstfxid = (('V' << 16) | ('S' << 8) | (forControllerUID ? 'E' : 'T'));
  1128. char vstfxidStr[7] = { 0 };
  1129. sprintf (vstfxidStr, "%06X", vstfxid);
  1130. strcpy (uidString, vstfxidStr);
  1131. char uidStr[9] = { 0 };
  1132. sprintf (uidStr, "%08X", JucePlugin_VSTUniqueID);
  1133. strcat (uidString, uidStr);
  1134. char nameidStr[3] = { 0 };
  1135. const size_t len = strlen (JucePlugin_Name);
  1136. for (size_t i = 0; i <= 8; ++i)
  1137. {
  1138. juce::uint8 c = i < len ? JucePlugin_Name[i] : 0;
  1139. if (c >= 'A' && c <= 'Z')
  1140. c += 'a' - 'A';
  1141. sprintf (nameidStr, "%02X", c);
  1142. strcat (uidString, nameidStr);
  1143. }
  1144. FUID newOne;
  1145. newOne.fromString (uidString);
  1146. return newOne;
  1147. }
  1148. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1149. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1150. #else
  1151. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1152. DEF_CLASS_IID (JuceVST3EditController)
  1153. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1154. DEF_CLASS_IID (JuceVST3Component)
  1155. #endif
  1156. #if JUCE_MSVC
  1157. #pragma warning (pop)
  1158. #elif JUCE_CLANG
  1159. #pragma clang diagnostic pop
  1160. #endif
  1161. //==============================================================================
  1162. bool initModule()
  1163. {
  1164. #if JUCE_MAC
  1165. initialiseMac();
  1166. #endif
  1167. return true;
  1168. }
  1169. bool shutdownModule()
  1170. {
  1171. return true;
  1172. }
  1173. #undef JUCE_EXPORTED_FUNCTION
  1174. #if JUCE_WINDOWS
  1175. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1176. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1177. #define JUCE_EXPORTED_FUNCTION
  1178. #else
  1179. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1180. CFBundleRef globalBundleInstance = nullptr;
  1181. juce::uint32 numBundleRefs = 0;
  1182. juce::Array<CFBundleRef> bundleRefs;
  1183. enum { MaxPathLength = 2048 };
  1184. char modulePath[MaxPathLength] = { 0 };
  1185. void* moduleHandle = nullptr;
  1186. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1187. {
  1188. if (ref != nullptr)
  1189. {
  1190. ++numBundleRefs;
  1191. CFRetain (ref);
  1192. bundleRefs.add (ref);
  1193. if (moduleHandle == nullptr)
  1194. {
  1195. globalBundleInstance = ref;
  1196. moduleHandle = ref;
  1197. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1198. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1199. CFRelease (tempURL);
  1200. }
  1201. }
  1202. return initModule();
  1203. }
  1204. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1205. {
  1206. if (shutdownModule())
  1207. {
  1208. if (--numBundleRefs == 0)
  1209. {
  1210. for (int i = 0; i < bundleRefs.size(); ++i)
  1211. CFRelease (bundleRefs.getUnchecked (i));
  1212. bundleRefs.clear();
  1213. }
  1214. return true;
  1215. }
  1216. return false;
  1217. }
  1218. #endif
  1219. //==============================================================================
  1220. /** This typedef represents VST3's createInstance() function signature */
  1221. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1222. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1223. {
  1224. return (Vst::IAudioProcessor*) new JuceVST3Component (host);
  1225. }
  1226. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1227. {
  1228. return (Vst::IEditController*) new JuceVST3EditController (host);
  1229. }
  1230. //==============================================================================
  1231. class JucePluginFactory;
  1232. static JucePluginFactory* globalFactory = nullptr;
  1233. //==============================================================================
  1234. class JucePluginFactory : public IPluginFactory3
  1235. {
  1236. public:
  1237. JucePluginFactory()
  1238. : refCount (1),
  1239. factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1240. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1241. {
  1242. }
  1243. virtual ~JucePluginFactory()
  1244. {
  1245. if (globalFactory == this)
  1246. globalFactory = nullptr;
  1247. }
  1248. //==============================================================================
  1249. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1250. {
  1251. if (createFunction == nullptr)
  1252. {
  1253. jassertfalse;
  1254. return false;
  1255. }
  1256. ClassEntry* entry = classes.add (new ClassEntry (info, createFunction));
  1257. entry->infoW.fromAscii (info);
  1258. return true;
  1259. }
  1260. bool isClassRegistered (const FUID& cid) const
  1261. {
  1262. for (int i = 0; i < classes.size(); ++i)
  1263. if (classes.getUnchecked (i)->infoW.cid == cid)
  1264. return true;
  1265. return false;
  1266. }
  1267. //==============================================================================
  1268. JUCE_DECLARE_VST3_COM_REF_METHODS
  1269. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1270. {
  1271. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  1272. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  1273. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  1274. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  1275. jassertfalse; // Something new?
  1276. *obj = nullptr;
  1277. return kNotImplemented;
  1278. }
  1279. //==============================================================================
  1280. Steinberg::int32 PLUGIN_API countClasses() override
  1281. {
  1282. return (Steinberg::int32) classes.size();
  1283. }
  1284. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1285. {
  1286. if (info == nullptr)
  1287. return kInvalidArgument;
  1288. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  1289. return kResultOk;
  1290. }
  1291. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  1292. {
  1293. return getPClassInfo<PClassInfo> (index, info);
  1294. }
  1295. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  1296. {
  1297. return getPClassInfo<PClassInfo2> (index, info);
  1298. }
  1299. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  1300. {
  1301. if (info != nullptr)
  1302. {
  1303. if (ClassEntry* entry = classes[(int) index])
  1304. {
  1305. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  1306. return kResultOk;
  1307. }
  1308. }
  1309. return kInvalidArgument;
  1310. }
  1311. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  1312. {
  1313. *obj = nullptr;
  1314. FUID sourceFuid = sourceIid;
  1315. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  1316. {
  1317. jassertfalse; // The host you're running in has severe implementation issues!
  1318. return kInvalidArgument;
  1319. }
  1320. TUID iidToQuery;
  1321. sourceFuid.toTUID (iidToQuery);
  1322. for (int i = 0; i < classes.size(); ++i)
  1323. {
  1324. const ClassEntry& entry = *classes.getUnchecked (i);
  1325. if (doUIDsMatch (entry.infoW.cid, cid))
  1326. {
  1327. if (FUnknown* const instance = entry.createFunction (host))
  1328. {
  1329. const FReleaser releaser (instance);
  1330. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  1331. return kResultOk;
  1332. }
  1333. break;
  1334. }
  1335. }
  1336. return kNoInterface;
  1337. }
  1338. tresult PLUGIN_API setHostContext (FUnknown* context) override
  1339. {
  1340. host.loadFrom (context);
  1341. if (host != nullptr)
  1342. {
  1343. Vst::String128 name;
  1344. host->getName (name);
  1345. return kResultTrue;
  1346. }
  1347. return kNotImplemented;
  1348. }
  1349. private:
  1350. //==============================================================================
  1351. const JuceLibraryRefCount juceCount;
  1352. Atomic<int> refCount;
  1353. const PFactoryInfo factoryInfo;
  1354. ComSmartPtr<Vst::IHostApplication> host;
  1355. //==============================================================================
  1356. struct ClassEntry
  1357. {
  1358. ClassEntry() noexcept : createFunction (nullptr), isUnicode (false) {}
  1359. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  1360. : info2 (info), createFunction (fn), isUnicode (false) {}
  1361. PClassInfo2 info2;
  1362. PClassInfoW infoW;
  1363. CreateFunction createFunction;
  1364. bool isUnicode;
  1365. private:
  1366. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  1367. };
  1368. OwnedArray<ClassEntry> classes;
  1369. //==============================================================================
  1370. template<class PClassInfoType>
  1371. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  1372. {
  1373. if (info != nullptr)
  1374. {
  1375. zerostruct (*info);
  1376. if (ClassEntry* entry = classes[(int) index])
  1377. {
  1378. if (entry->isUnicode)
  1379. return kResultFalse;
  1380. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  1381. return kResultOk;
  1382. }
  1383. }
  1384. jassertfalse;
  1385. return kInvalidArgument;
  1386. }
  1387. //==============================================================================
  1388. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  1389. };
  1390. } // juce namespace
  1391. //==============================================================================
  1392. #ifndef JucePlugin_Vst3ComponentFlags
  1393. #if JucePlugin_IsSynth
  1394. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  1395. #else
  1396. #define JucePlugin_Vst3ComponentFlags 0
  1397. #endif
  1398. #endif
  1399. #ifndef JucePlugin_Vst3Category
  1400. #if JucePlugin_IsSynth
  1401. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  1402. #else
  1403. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  1404. #endif
  1405. #endif
  1406. //==============================================================================
  1407. // The VST3 plugin entry point.
  1408. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  1409. {
  1410. #if JUCE_WINDOWS
  1411. // Cunning trick to force this function to be exported. Life's too short to
  1412. // faff around creating .def files for this kind of thing.
  1413. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  1414. #endif
  1415. if (globalFactory == nullptr)
  1416. {
  1417. globalFactory = new JucePluginFactory();
  1418. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  1419. PClassInfo::kManyInstances,
  1420. kVstAudioEffectClass,
  1421. JucePlugin_Name,
  1422. JucePlugin_Vst3ComponentFlags,
  1423. JucePlugin_Vst3Category,
  1424. JucePlugin_Manufacturer,
  1425. JucePlugin_VersionString,
  1426. kVstVersionString);
  1427. globalFactory->registerClass (componentClass, createComponentInstance);
  1428. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  1429. PClassInfo::kManyInstances,
  1430. kVstComponentControllerClass,
  1431. JucePlugin_Name,
  1432. JucePlugin_Vst3ComponentFlags,
  1433. JucePlugin_Vst3Category,
  1434. JucePlugin_Manufacturer,
  1435. JucePlugin_VersionString,
  1436. kVstVersionString);
  1437. globalFactory->registerClass (controllerClass, createControllerInstance);
  1438. }
  1439. else
  1440. {
  1441. globalFactory->addRef();
  1442. }
  1443. return dynamic_cast<IPluginFactory*> (globalFactory);
  1444. }
  1445. #endif //JucePlugin_Build_VST3