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.

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