/// <summary> /// Gets a copy of the current image being displayed by the video renderer. /// </summary> /// <param name="videoDisplayControl">A valid IMFVideoDisplayControl instance.</param> /// <param name="bih">A BitmapInfoHeader class that receives a description of the bitmap. </param> /// <param name="dib">Receives byte array that contains a packed Windows device-independent bitmap (DIB).</param> /// <param name="timeStamp">Receives the time stamp of the captured image.</param> /// <returns>If this function succeeds, it returns the S_OK member. Otherwise, it returns another HResult's member that describe the error.</returns> public static HResult GetCurrentImage(this IMFVideoDisplayControl videoDisplayControl, BitmapInfoHeader bih, out byte[] dib, out TimeSpan timeStamp) { if (videoDisplayControl == null) { throw new ArgumentNullException("videoDisplayControl"); } IntPtr dibPtr; int dibLength; long time; HResult hr = videoDisplayControl.GetCurrentImage(bih, out dibPtr, out dibLength, out time); if (hr.Succeeded()) { try { dib = new byte[dibLength]; Marshal.Copy(dibPtr, dib, 0, dibLength); timeStamp = TimeSpan.FromTicks(time); } finally { Marshal.FreeCoTaskMem(dibPtr); } } else { dib = null; timeStamp = TimeSpan.MinValue; } return(hr); }
protected override void Initialize(IGraphBuilder pGraphBuilder, IntPtr hMediaWindow) { object factoryObject = null; object presenterObject = null; try { int hr = ClassFactory.GetEvrPresenterClassFactory(ref CLSID_CustomEVRPresenter, ref ClassFactory.IID_ClassFactory, out factoryObject); Marshal.ThrowExceptionForHR(hr); IClassFactory factory = (IClassFactory)factoryObject; var iidPresenter = typeof(IMFVideoPresenter).GUID; hr = factory.CreateInstance(null, ref iidPresenter, out presenterObject); Marshal.ThrowExceptionForHR(hr); IMFVideoPresenter presenter = (IMFVideoPresenter)presenterObject; IMFVideoRenderer renderer = (IMFVideoRenderer)BaseFilter; // will be released when IBaseFilter is released renderer.InitializeRenderer(null, presenter); IMFGetService pMFGetService = (IMFGetService)BaseFilter; // will be released when IBaseFilter is released object o; var serviceId = ServiceID.EnhancedVideoRenderer; var iidImfVideoDisplayControl = typeof(IMFVideoDisplayControl).GUID; Marshal.ThrowExceptionForHR(pMFGetService.GetService(ref serviceId, ref iidImfVideoDisplayControl, out o)); _pMFVideoDisplayControl = (IMFVideoDisplayControl)o; _pMFVideoDisplayControl.SetVideoWindow(hMediaWindow); _pMFVideoDisplayControl.SetAspectRatioMode(MFVideoAspectRatioMode.MFVideoARMode_None); _pvpPresenterConfig = (IPvpPresenterConfig)presenterObject; _pvpPresenterConfig.SetBufferCount(PRESENTER_BUFFER_COUNT); _pvpPresenterHook.HookUp(presenterObject); // as EVR requests IMFVideoDisplayControl from the presenter and our custom presenter implements IPvpPresenter and IPvpPresenterConfig // presenterObject and _pMFVideoDisplayControl point to the same RCW presenterObject = null; // we will release the presenter when releasing _pMFVideoDisplayControl } catch { _pMFVideoDisplayControl = null; _pvpPresenterConfig = null; } finally { if (factoryObject != null) { Marshal.FinalReleaseComObject(factoryObject); } if (presenterObject != null) { Marshal.FinalReleaseComObject(presenterObject); } } }
public void SetRendererInterfaces(IVMRWindowlessControl VMRWindowlessControl, IVMRWindowlessControl9 VMRWindowlessControl9, IMFVideoDisplayControl MFVideoDisplayControl) { _VMRWindowlessControl = VMRWindowlessControl; _VMRWindowlessControl9 = VMRWindowlessControl9; _MFVideoDisplayControl = MFVideoDisplayControl; }
/// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Close down all media devices /// </summary> /// <history> /// 01 Nov 18 Cynic - Originally Written /// </history> public void CloseAllMediaDevices() { LogMessage("CloseAllMediaDevices called"); // we do not release this here. The entity that gave this // to us is expected to release it. evrVideoDisplay = null; }
private void TearDownGraph() { #if DEBUG if (m_rot != null) { m_rot.Dispose(); m_rot = null; } #endif // Stop sending event messages if (m_pEvent != null) { m_pEvent.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); m_pEvent = null; } if (m_pControl != null) { m_pControl.Stop(); m_pControl = null; } if (m_pDisplay != null) { //Marshal.ReleaseComObject(m_pDisplay); m_pDisplay = null; } if (m_pMapper != null) { Marshal.ReleaseComObject(m_pMapper); m_pMapper = null; } if (m_pMixer != null) { Marshal.ReleaseComObject(m_pMixer); m_pMixer = null; } if (m_pEVR != null) { Marshal.ReleaseComObject(m_pEVR); m_pEVR = null; } if (m_pGraph != null) { Marshal.ReleaseComObject(m_pGraph); m_pGraph = null; } m_state = PlaybackState.Closed; m_seekCaps = 0; m_pSeek = null; }
private void GetInterface2() { object o; IMFGetService gs = new MFVideoPresenter9() as IMFGetService; int hr = gs.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o); MFError.ThrowExceptionForHR(hr); m_vdc = o as IMFVideoDisplayControl; }
protected override void CloseInterfaces() { if (_pMfVideoDisplayControl != null) { _pMfVideoDisplayControl.SetVideoWindow(IntPtr.Zero); Marshal.FinalReleaseComObject(_pMfVideoDisplayControl); _pMfVideoDisplayControl = null; } base.CloseInterfaces(); // release pBaseFilter }
public VideoInternalWindow(string caption, IMFVideoDisplayControl evr) { InitializeComponent(); _evr = evr; _isInit = false; _filterName = caption; this.Resize += new EventHandler(VideoInternalWindow_Resize); this.Paint += new PaintEventHandler(VideoInternalWindow_Paint); this.MouseMove += new MouseEventHandler(VideoInternalWindow_MouseMove); this.MouseDown += new MouseEventHandler(VideoInternalWindow_MouseDown); }
/// <summary> /// Closes and releases all used interfaces. /// </summary> public void CloseInterfaces() { if (VMRenderer != null) { Marshal.ReleaseComObject(VMRenderer); VMRenderer = null; WindowlessCtrl = null; IMFVideoDisplayControl = null; MixerBitmap = null; } if (Processer != null) { Marshal.ReleaseComObject(Processer); AudioRender = null; } if (AudioRender != null) { Marshal.ReleaseComObject(AudioRender); AudioRender = null; } if (FilterGraph != null) { Marshal.ReleaseComObject(FilterGraph); FilterGraph = null; MediaControl = null; } if (SmartTee != null) { Marshal.ReleaseComObject(SmartTee); SmartTee = null; } if (SampleGrabber != null) { Marshal.ReleaseComObject(SampleGrabber); SampleGrabber = null; SampleGrabberFilter = null; } if (CaptureFilter != null) { Marshal.ReleaseComObject(CaptureFilter); CaptureFilter = null; } if (Crossbar != null) { Marshal.ReleaseComObject(Crossbar); Crossbar = null; } }
private void FillWindow() { if (pDisplay == null) { return; } IMFVideoDisplayControl mfVideoDisplayControl = pDisplay; Rectangle r = panel.ClientRectangle; MediaFoundation.Misc.MFRect rc = new MediaFoundation.Misc.MFRect(r.Left, r.Top, r.Right, r.Bottom); mfVideoDisplayControl.SetVideoPosition(null, rc); }
public MFMediaUriPlayer(IntPtr hVideo, IntPtr hEvent) { Debug.Assert(hVideo != IntPtr.Zero); Debug.Assert(hEvent != IntPtr.Zero); m_pSession = null; m_pSource = null; m_pVideoDisplay = null; m_hwndVideo = hVideo; m_hwndEvent = hEvent; m_state = PlayerState.Ready; m_hCloseEvent = new AutoResetEvent(false); MFExtern.MFStartup(0x10070, MFStartup.Full); }
/// <summary> /// Init /// </summary> /// <param name="hVideo"></param> /// <param name="hEvent"></param> public Media(IntPtr hVideo, IntPtr hEvent) { TRACE("Media::Media"); Debug.Assert(hVideo != IntPtr.Zero); Debug.Assert(hEvent != IntPtr.Zero); m_pSession = null; m_pSource = null; m_pVideoDisplay = null; m_hwndVideo = hVideo; m_hwndEvent = hEvent; m_state = MediaState.Ready; m_hCloseEvent = new AutoResetEvent(false); MFExtern.MFStartup(MF_VERSION, MFStartup.Full); }
public DShowPlayer(Control hwndVideo, IntPtr hwnd, int msg) { m_state = PlaybackState.Closed; m_hwndVideo = hwndVideo; m_hwndEvent = hwnd; m_EventMsg = msg; m_pGraph = null; m_pControl = null; m_pEvent = null; m_pSeek = null; m_pDisplay = null; m_pEVR = null; m_pMapper = null; m_seekCaps = 0; m_clsidPresenter = Guid.Empty; }
private void GetInterface() { object o; IMFActivate pRendererActivate = null; System.Windows.Forms.Form f = new System.Windows.Forms.Form(); int hr = MFExtern.MFCreateVideoRendererActivate(IntPtr.Zero, out pRendererActivate); MFError.ThrowExceptionForHR(hr); hr = pRendererActivate.ActivateObject(typeof(IMFGetService).GUID, out o); MFError.ThrowExceptionForHR(hr); IMFGetService imfs = o as IMFGetService; hr = imfs.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o); MFError.ThrowExceptionForHR(hr); m_vdc = o as IMFVideoDisplayControl; }
private void InitializeEVR(IBaseFilter pEVR, int dwStreams, out IMFVideoDisplayControl ppDisplay) { IMFVideoRenderer pRenderer; IEVRFilterConfig pConfig; IMFVideoPresenter pPresenter; pPresenter = new EVRCustomPresenter(); pRenderer = (IMFVideoRenderer)pEVR; pRenderer.InitializeRenderer(null, pPresenter); object o; MediaFoundation.IMFGetService pGetService; pGetService = (MediaFoundation.IMFGetService)pEVR; pGetService.GetService(MediaFoundation.MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o); try { pDisplay = (IMFVideoDisplayControl)o; } catch { Marshal.ReleaseComObject(o); throw; } pDisplay.SetVideoWindow(panel.Handle); if (dwStreams > 1) { pConfig = (IEVRFilterConfig)pEVR; pConfig.SetNumberOfStreams(dwStreams); } Rectangle r = ClientRectangle; MediaFoundation.Misc.MFRect rc = new MediaFoundation.Misc.MFRect(r.Left, r.Top, r.Right, r.Bottom); pDisplay.SetVideoPosition(null, rc); ppDisplay = pDisplay; }
public CPlayer(IntPtr hVideo, IntPtr hEvent) { TRACE(("CPlayer::CPlayer")); Debug.Assert(hVideo != IntPtr.Zero); Debug.Assert(hEvent != IntPtr.Zero); m_pSession = null; m_pSource = null; m_pVideoDisplay = null; m_hwndVideo = hVideo; m_hwndEvent = hEvent; m_state = PlayerState.Ready; m_hCloseEvent = new AutoResetEvent(false); int hr = MFExtern.MFStartup(0x10070, MFStartup.Full); MFError.ThrowExceptionForHR(hr); }
protected override void Initialize(IGraphBuilder pGraphBuilder, IntPtr hMediaWindow) { // QUERY the EVR interfaces try { IMFGetService pMFGetService = (IMFGetService)BaseFilter; // will be released when IBaseFilter is released object o; Guid serviceId = ServiceID.EnhancedVideoRenderer; Guid IID_IMFVideoDisplayControl = typeof(IMFVideoDisplayControl).GUID; Marshal.ThrowExceptionForHR(pMFGetService.GetService(ref serviceId, ref IID_IMFVideoDisplayControl, out o)); _pMfVideoDisplayControl = (IMFVideoDisplayControl)o; _pMfVideoDisplayControl.SetVideoWindow(hMediaWindow); _pMfVideoDisplayControl.SetAspectRatioMode(MFVideoAspectRatioMode.MFVideoARMode_None); } catch (Exception e) { throw new FilterGraphBuilderException(GraphBuilderError.ConfigureEVR, e); } }
// Media event handlers /// <summary> /// Handle TopologyReady Event /// </summary> /// <param name="pEvent"></param> protected void OnTopologyReady(IMFMediaEvent pEvent) { object o; TRACE("Media::OnTopologyReady"); // Ask for the IMFVideoDisplayControl interface. // This interface is implemented by the EVR and is // exposed by the media session as a service. // Note: This call is expected to fail if the source // does not have video. try { MFExtern.MFGetService( m_pSession, MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o ); m_pVideoDisplay = o as IMFVideoDisplayControl; } catch (InvalidCastException) { m_pVideoDisplay = null; } try { StartPlayback(); } catch (Exception e) { int hr = Marshal.GetHRForException(e); NotifyError(hr); } // If we succeeded, the Start call is pending. Don't notify the app yet. }
/// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } if (_vw != null) { int hr = _vw.put_Owner(IntPtr.Zero); _vw = null; } if (_evr != null) { try { _evr.SetVideoWindow(IntPtr.Zero); } catch (Exception ex) { #if DEBUG MessageBox.Show(ex.Message, "Failed to reset EVR Window"); #endif } finally { _evr = null; } } if (_detachedWindow != null) { _detachedWindow.Close(); } base.Dispose(disposing); }
/// <summary> /// Close a Media Session /// </summary> protected void CloseSession() { if (m_pVideoDisplay != null) { Marshal.ReleaseComObject(m_pVideoDisplay); m_pVideoDisplay = null; } if (m_pSession != null) { m_pSession.Close(); // Wait for the close operation to complete bool res = m_hCloseEvent.WaitOne(WAIT_TIMEOUT, true); if (!res) { TRACE("WaitForSingleObject Timed Out !"); } } // Complete shutdown operations // 1. Shut down the media source if (m_pSource != null) { m_pSource.Shutdown(); SafeRelease(m_pSource); m_pSource = null; } // 2. Shut down the media session. (Synchronous operation, no events.) if (m_pSession != null) { m_pSession.Shutdown(); Marshal.ReleaseComObject(m_pSession); m_pSession = null; } }
private void InitializeEvr(DirectShowLib.IBaseFilter pEvr, int dwStreams) { IMFVideoDisplayControl pDisplay; // Continue with the rest of the set-up. // Set the video window. object o; var pGetService = (IMFGetService)pEvr; var hr = pGetService.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o); DsError.ThrowExceptionForHR(hr); try { pDisplay = (IMFVideoDisplayControl)o; } catch { Marshal.ReleaseComObject(o); throw; } // Set the number of streams. hr = pDisplay.SetVideoWindow(VideoWindowHandle); DsError.ThrowExceptionForHR(hr); if (dwStreams > 1) { var pConfig = (IEVRFilterConfig)pEvr; hr = pConfig.SetNumberOfStreams(dwStreams); DsError.ThrowExceptionForHR(hr); } // Return the IMFVideoDisplayControl pointer to the caller. _mPDisplay = pDisplay; }
private void CloseInterfaces() { int hr = 0; try { lock (locker) { // Relinquish ownership (IMPORTANT!) after hiding video window if (!this.IsAudioOnly && this.videoWindow != null) { hr = this.videoWindow.put_Visible(OABool.False); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_Owner(IntPtr.Zero); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_MessageDrain(IntPtr.Zero); DsError.ThrowExceptionForHR(hr); } if (EVRControl != null) { Marshal.ReleaseComObject(EVRControl); EVRControl = null; } if (this.mediaEventEx != null) { hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); this.mediaEventEx = null; } // Release and zero DirectShow interfaces if (this.mediaSeeking != null) this.mediaSeeking = null; if (this.mediaPosition != null) this.mediaPosition = null; if (this.mediaControl != null) this.mediaControl = null; if (this.basicAudio != null) this.basicAudio = null; if (this.basicVideo != null) this.basicVideo = null; if (this.videoWindow != null) this.videoWindow = null; if (this.graphBuilder != null) { while (Marshal.ReleaseComObject(this.graphBuilder) > 0) ; this.graphBuilder = null; } //bad way //if (this.graphBuilder != null) //Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null; GC.Collect(); } } catch (Exception ex) { ErrorException("CloseInterfaces: " + ex.Message, ex.StackTrace); } }
/// <summary> /// Event that is raised after a DaggerNode has been created and associated to the UI element /// </summary> /// <param name="node"></param> void DSFilterNodeUI_DaggerNodeAttached(DaggerLib.Core.DaggerNode node) { _dsfilternode = (DSFilterNode)node; CaptionText = node.ToString(); // hook the AfterNodeRemoved event to dispose of any directshow interfaces node.AfterNodeRemoved += new DaggerLib.Core.AfterNodeRemoveHandler(node_AfterNodeRemoved); // get the IBaseFilter from the DSFilterNode IBaseFilter filter = _dsfilternode._filter; // only grab the video window or EVR if it was manually added to the graph via the UI if (_dsfilternode._manualAdded || (_dsfilternode.ParentGraph.ParentUIGraph as DSDaggerUIGraph)._filterGraphCreated) { // if it supports IVideoWindow create a VideoInternalWindow for it IVideoWindow vw = filter as IVideoWindow; if (vw != null) { try { _videoWindow = new VideoInternalWindow(CaptionText, filter); _videoWindow.Dock = DockStyle.Fill; _videoWindow.Visible = true; InternalControl.Controls.Add(_videoWindow); // only nodes with video windows are resizeable Resizable = true; // hook the connection events to init/deinit the video window node.ParentGraph.AfterPinsConnected += new DaggerLib.Core.PinAfterConnectedHandler(ParentGraph_AfterPinsConnected); } catch (Exception ex) { #if DEBUG MessageBox.Show(ex.Message); #endif _videoWindow = null; } } // if it's an Enhaced Video Renderer create a VideoInternalWindow for it // (see docs for Windows Media Foundation) IMFGetService mfgs = filter as IMFGetService; if (mfgs != null) { // this is a video horse of a different color // create a video clipping window for the Media Foundation Enhanced Video Renderer try { // get the IMFVideoDisplayControl for the EVR filter object o = null; mfgs.GetService(MediaFoundation.MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o ); m_pVideoDisplay = o as IMFVideoDisplayControl; // if the Video Size is 0,0 the EVR hasn't been initialized/connected yet MediaFoundation.Misc.SIZE videoSize = new MediaFoundation.Misc.SIZE(); MediaFoundation.Misc.SIZE ar = new MediaFoundation.Misc.SIZE(); m_pVideoDisplay.GetNativeVideoSize(videoSize, ar); if (videoSize.cx == 0 && videoSize.cy == 0) { // You only get one chance to set the number of pins in an EVR filter. PinsComboBoxForm pcf = new PinsComboBoxForm(); if (pcf.ShowDialog() == DialogResult.OK) { (filter as IEVRFilterConfig).SetNumberOfStreams(pcf.Value); } pcf.Dispose(); } _videoWindow = new VideoInternalWindow(CaptionText, m_pVideoDisplay); _videoWindow.Dock = DockStyle.Fill; _videoWindow.Visible = true; InternalControl.Controls.Add(_videoWindow); // only nodes with video windows are resizeable Resizable = true; // hook the connection events to init/deinit the video window node.ParentGraph.AfterPinsConnected += new DaggerLib.Core.PinAfterConnectedHandler(ParentGraph_AfterPinsConnected); } catch (InvalidCastException) { m_pVideoDisplay = null; } } } // if it's a DMO, create the DMO properties page for it if ((filter as IDMOWrapperFilter) != null) { // set the caption to show it's a DMO CaptionText = "DMO - " + CaptionText; CaptionColor = Color.Green; CaptionColorUnfocused = Color.LightGreen; } // remove clock button if it doesn't support IReferenceClock _referenceClock = filter as IReferenceClock; if (_referenceClock == null) { CaptionButtons.RemoveAt(CaptionButtons.AllButtons.IndexOf(_clockButton)); } else { // see if this filter is the reference clock for the graph IReferenceClock graphClock = null; filter.GetSyncSource(out graphClock); _clockButton.Tag = false; _clockButton.MouseOutsideTint = Color.DarkGray; if (graphClock != null) { if (graphClock == _referenceClock) { _clockButton.MouseOutsideTint = Color.Yellow; _clockButton.Tag = true; } Marshal.ReleaseComObject(graphClock); } } // remove video window button if it's not a video window if (_videoWindow == null) { CaptionButtons.RemoveAt(CaptionButtons.AllButtons.IndexOf(_detachVideoWindowButton)); } // Sync the pins to the Pin Property Pages SyncPinPropertyPages(null); // set it to the smallest possible size. DaggerLib uses InternalControlMinimumSize // to prevent the UI node from being smaller than designated this.Size = new Size(1, 1); }
private void CloseInterfaces() { _hiddenWindow.SizeChanged -= _hiddenWindow_SizeChanged; int hr; if (_defaultAudioRenderer != null) { m_graph.RemoveFilter(_defaultAudioRenderer as DirectShowLib.IBaseFilter); Marshal.ReleaseComObject(_defaultAudioRenderer); _defaultAudioRenderer = null; } if (_reclockAudioRenderer != null) { m_graph.RemoveFilter(_reclockAudioRenderer as DirectShowLib.IBaseFilter); Marshal.ReleaseComObject(_reclockAudioRenderer); _reclockAudioRenderer = null; } if (_lavaudio != null) { m_graph.RemoveFilter(_lavaudio as DirectShowLib.IBaseFilter); Marshal.ReleaseComObject(_lavaudio); _lavaudio = null; } if (_xyVsFilter != null) { m_graph.RemoveFilter(_xyVsFilter as DirectShowLib.IBaseFilter); Marshal.ReleaseComObject(_xyVsFilter); _xyVsFilter = null; } if (_xySubFilter != null) { m_graph.RemoveFilter(_xySubFilter as DirectShowLib.IBaseFilter); Marshal.ReleaseComObject(_xySubFilter); _xySubFilter = null; } if (_lavvideo != null) { m_graph.RemoveFilter(_lavvideo as DirectShowLib.IBaseFilter); Marshal.ReleaseComObject(_lavvideo); _lavvideo = null; } if (_madvr != null) { m_graph.RemoveFilter(_madvr as DirectShowLib.IBaseFilter); Marshal.ReleaseComObject(_madvr); _madvr = null; } if (_videoWindow != null) { // Relinquish ownership (IMPORTANT!) after hiding video window hr = _videoWindow.put_Visible(OABool.False); hr = _videoWindow.put_Owner(IntPtr.Zero); } if (_mediaEventEx != null) { hr = _mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); Marshal.ReleaseComObject(_mediaEventEx); _mediaEventEx = null; } if (_dvdNav != null) { Marshal.ReleaseComObject(_dvdNav); _dvdNav = null; } if (_mDvdInfo != null) { Marshal.ReleaseComObject(_mDvdInfo); _mDvdInfo = null; } if (_mDvdControl != null) { Marshal.ReleaseComObject(_mDvdControl); _mDvdControl = null; } if (_mPDisplay != null) { Marshal.ReleaseComObject(_mPDisplay); _mPDisplay = null; } if (_filterGraph != null) { Marshal.ReleaseComObject(_filterGraph); _filterGraph = null; } if (_mPEvr != null) { Marshal.ReleaseComObject(_mPEvr); _mPEvr = null; } if (_mediaEventEx != null) { Marshal.ReleaseComObject(_mediaEventEx); _mediaEventEx = null; } if (_mediaSeeking != null) { Marshal.ReleaseComObject(_mediaSeeking); _mediaSeeking = null; } if (_mediaPosition != null) { Marshal.ReleaseComObject(_mediaPosition); _mediaPosition = null; } if (_mediaControl != null) { Marshal.ReleaseComObject(_mediaControl); _mediaControl = null; } if (_basicAudio != null) { Marshal.ReleaseComObject(_basicAudio); _basicAudio = null; } if (_basicVideo != null) { Marshal.ReleaseComObject(_basicVideo); _basicVideo = null; } if (_sourceFilter != null) { Marshal.ReleaseComObject(_sourceFilter); _sourceFilter = null; } if (m_graph != null) { Marshal.ReleaseComObject(m_graph); m_graph = null; } if (_videoWindow != null) { Marshal.ReleaseComObject(_videoWindow); _videoWindow = null; } _mSeekCaps = 0; _streams = null; GC.Collect(); }
// Media event handlers protected void OnTopologyReady(IMFMediaEvent pEvent) { object o; TRACE("CPlayer::OnTopologyReady"); // Ask for the IMFVideoDisplayControl interface. // This interface is implemented by the EVR and is // exposed by the media session as a service. // Note: This call is expected to fail if the source // does not have video. try { MFExtern.MFGetService( m_pSession, MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o ); m_pVideoDisplay = o as IMFVideoDisplayControl; } catch (InvalidCastException) { m_pVideoDisplay = null; } try { StartPlayback(); } catch (Exception ce) { int hr = Marshal.GetHRForException(ce); NotifyError(hr); } // If we succeeded, the Start call is pending. Don't notify the app yet. }
private void SetupEvrDisplay() { IMFGetService mfgs = evrRenderer as IMFGetService; if (mfgs != null) { try { object objDisplay = null; mfgs.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out objDisplay ); FileLogger.Log("PlayMovieInWindow: MR_VIDEO_RENDER_SERVICE"); evrDisplay = objDisplay as IMFVideoDisplayControl; MediaFoundation.Misc.MFSize videoSize = new MediaFoundation.Misc.MFSize(); MediaFoundation.Misc.MFSize ar = new MediaFoundation.Misc.MFSize(); evrDisplay.GetNativeVideoSize(videoSize, ar); if ((videoSize.cx == 0 && videoSize.cy == 0) || videoSize.cx <= 0) { IEVRFilterConfig evrConfig = evrRenderer as IEVRFilterConfig; int pdwMaxStreams; evrConfig.GetNumberOfStreams(out pdwMaxStreams); FileLogger.Log("NumberOfStreams: {0}", pdwMaxStreams); if (pdwMaxStreams < 1) { evrConfig.SetNumberOfStreams(1); FileLogger.Log("Set NumberOfStreams: {0}", 1); } } //object objMemConfig = null; //mfgs.GetService(MFServices.MR_VIDEO_ACCELERATION_SERVICE, typeof(IDirectXVideoMemoryConfiguration).GUID, out objMemConfig); } catch (InvalidCastException) { //do nothing } } }
public void InitializeMedia(string MediaFile, int dwrate, float dwvolume) { int hr; MFStartup(MF_VERSION, MFSTARTUP_FULL); MFCreateMediaSession(IntPtr.Zero, out IMFMediaSession mediaSession); MFCreateTopology(out IMFTopology topo); MFCreateSourceResolver(out IMFSourceResolver resolver); IUnknown unknown; try { resolver.CreateObjectFromURL(MediaFile, MF_RESOLUTION_MEDIASOURCE | MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE, null, out uint objtype, out unknown); } catch { MessageBox.Show("不支持的媒体格式。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } IMFMediaSource source = unknown as IMFMediaSource; source.CreatePresentationDescriptor(out IMFPresentationDescriptor descriptor); if (MFRequireProtectedEnvironment(descriptor) == 0) { MessageBox.Show("媒体受保护,无法播放。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } descriptor.GetStreamDescriptorCount(out uint sdcount); for (uint i = 0; i < sdcount; i++) { descriptor.GetStreamDescriptorByIndex(i, out bool IsSelected, out IMFStreamDescriptor sd); if (!IsSelected) { descriptor.SelectStream(i); } sd.GetMediaTypeHandler(out IMFMediaTypeHandler typeHandler); typeHandler.GetMajorType(out Guid streamtype); IMFActivate renderer; if (streamtype == MFMediaType_Audio) { hr = MFCreateAudioRendererActivate(out renderer); } else if (streamtype == MFMediaType_Video) { hr = MFCreateVideoRendererActivate(host.Handle, out renderer); hasvideo = true; } else { continue; } hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, out IMFTopologyNode sourcenode); sourcenode.SetUnknown(MF_TOPONODE_SOURCE, source as IUnknown); sourcenode.SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, descriptor as IUnknown); sourcenode.SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, sd as IUnknown); topo.AddNode(sourcenode); MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, out IMFTopologyNode outputnode); outputnode.SetObject(renderer as IUnknown); topo.AddNode(outputnode); hr = sourcenode.ConnectOutput(0, outputnode, 0); } mediaSession.SetTopology(0, topo); Hide(); uint eventtype = 0; while (eventtype != MESessionTopologyStatus) { mediaSession.GetEvent(0, out IMFMediaEvent mediaevent); mediaevent.GetType(out eventtype); mediaevent = null; } Guid guid_ratecontrol = typeof(IMFRateControl).GUID; MFGetService(mediaSession as IUnknown, ref MF_RATE_CONTROL_SERVICE, ref guid_ratecontrol, out IUnknown _ratecontrol); IMFRateControl ratecontrol = _ratecontrol as IMFRateControl; hr = ratecontrol.SetRate(false, dwrate >= 0 ? dwrate * 7 / 10 + 1 : 1 / (1 + dwrate / -10 * 7)); try { Guid guid_audiopolicy = typeof(IMFAudioPolicy).GUID; hr = MFGetService(mediaSession as IUnknown, ref MR_AUDIO_POLICY_SERVICE, ref guid_audiopolicy, out IUnknown _policy); IMFAudioPolicy policy = _policy as IMFAudioPolicy; policy.SetDisplayName(" "); playvolume = dwvolume; } catch { } try { Guid guid_videocontrol = typeof(IMFVideoDisplayControl).GUID; hr = MFGetService(mediaSession as IUnknown, ref MR_VIDEO_RENDER_SERVICE, ref guid_videocontrol, out IUnknown _videocontrol); IMFVideoDisplayControl videocontrol = _videocontrol as IMFVideoDisplayControl; if (FullScreen.Checked) { host.Top = 0; host.Left = 0; host.Width = (int)System.Windows.SystemParameters.PrimaryScreenWidth; host.Height = (int)System.Windows.SystemParameters.PrimaryScreenHeight; } Rectangle videopos = new Rectangle(0, 0, host.Width, host.Height); host.videocontrol = videocontrol; videocontrol.SetVideoPosition(null, ref videopos); } catch { } state = "Prepared"; while (true) { if (state == "Playing") { eventtype = 0; PropVariant prop = new PropVariant() { vt = (ushort)VarEnum.VT_I8, unionmember = 0, }; #region mediasession if (hasvideo) { host.Show(); } preventthread = new Thread(() => { while (true) { if (state == "Playing") { while (state == "Playing") { if (hasvideo) { host.BringToFront(); } SetAppAndSystemVolume(playvolume, false); } } } }); preventthread.Start(); hr = mediaSession.Start(Guid.Empty, prop); while (eventtype != MESessionEnded) { hr = mediaSession.GetEvent(1, out IMFMediaEvent mediaevent); if (hr == 0 && mediaevent != null) { mediaevent.GetType(out eventtype); mediaevent = null; } Application.DoEvents(); } host.Hide(); state = "Ended"; #endregion } } }
private void PlayMovieInWindow(string filename) { if (filename == string.Empty) return; int hr = 0; this.graphBuilder = (IGraphBuilder)new FilterGraph(); //Добавляем в граф нужный рендерер (Auto - graphBuilder сам выберет рендерер) Settings.VRenderers renderer = Settings.VideoRenderer; if (renderer == Settings.VRenderers.Overlay) { IBaseFilter add_vr = (IBaseFilter)new VideoRenderer(); hr = graphBuilder.AddFilter(add_vr, "Video Renderer"); DsError.ThrowExceptionForHR(hr); } else if (renderer == Settings.VRenderers.VMR7) { IBaseFilter add_vmr = (IBaseFilter)new VideoMixingRenderer(); hr = graphBuilder.AddFilter(add_vmr, "Video Renderer"); DsError.ThrowExceptionForHR(hr); } else if (renderer == Settings.VRenderers.VMR9) { IBaseFilter add_vmr9 = (IBaseFilter)new VideoMixingRenderer9(); hr = graphBuilder.AddFilter(add_vmr9, "Video Mixing Renderer 9"); DsError.ThrowExceptionForHR(hr); } else if (renderer == Settings.VRenderers.EVR) { //Создаём Win32-окно, т.к. использовать WPF-поверхность не получится VHost = new VideoHwndHost(); VHost.RepaintRequired += new EventHandler(VHost_RepaintRequired); VHostElement.Child = VHost; VHandle = VHost.Handle; //Добавляем и настраиваем EVR IBaseFilter add_evr = (IBaseFilter)new EnhancedVideoRenderer(); hr = graphBuilder.AddFilter(add_evr, "Enhanced Video Renderer"); DsError.ThrowExceptionForHR(hr); object obj; IMFGetService pGetService = null; pGetService = (IMFGetService)add_evr; hr = pGetService.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out obj); MFError.ThrowExceptionForHR(hr); try { EVRControl = (IMFVideoDisplayControl)obj; } catch { Marshal.ReleaseComObject(obj); throw; } //Указываем поверхность hr = EVRControl.SetVideoWindow(VHandle); MFError.ThrowExceptionForHR(hr); //Отключаем сохранение аспекта hr = EVRControl.SetAspectRatioMode(MFVideoAspectRatioMode.None); MFError.ThrowExceptionForHR(hr); } // Have the graph builder construct its the appropriate graph automatically hr = this.graphBuilder.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); if (EVRControl == null) { //Ищем рендерер и отключаем соблюдение аспекта (аспект будет определяться размерами видео-окна) IBaseFilter filter = null; graphBuilder.FindFilterByName("Video Renderer", out filter); if (filter != null) { IVMRAspectRatioControl vmr = filter as IVMRAspectRatioControl; if (vmr != null) DsError.ThrowExceptionForHR(vmr.SetAspectRatioMode(VMRAspectRatioMode.None)); } else { graphBuilder.FindFilterByName("Video Mixing Renderer 9", out filter); if (filter != null) { IVMRAspectRatioControl9 vmr9 = filter as IVMRAspectRatioControl9; if (vmr9 != null) DsError.ThrowExceptionForHR(vmr9.SetAspectRatioMode(VMRAspectRatioMode.None)); } } } // QueryInterface for DirectShow interfaces this.mediaControl = (IMediaControl)this.graphBuilder; this.mediaEventEx = (IMediaEventEx)this.graphBuilder; this.mediaSeeking = (IMediaSeeking)this.graphBuilder; this.mediaPosition = (IMediaPosition)this.graphBuilder; // Query for video interfaces, which may not be relevant for audio files this.videoWindow = (EVRControl == null) ? this.graphBuilder as IVideoWindow : null; this.basicVideo = (EVRControl == null) ? this.graphBuilder as IBasicVideo : null; // Query for audio interfaces, which may not be relevant for video-only files this.basicAudio = this.graphBuilder as IBasicAudio; basicAudio.put_Volume(-(int)(10000 - Math.Pow(Settings.VolumeLevel, 1.0 / 5) * 10000)); //Громкость для ДиректШоу // Is this an audio-only file (no video component)? CheckIsAudioOnly(); if (!this.isAudioOnly) { //Определяем аспект, если он нам не известен if (in_ar == 0) { MediaInfoWrapper media = new MediaInfoWrapper(); media.Open(filepath); in_ar = media.Aspect; media.Close(); } if (videoWindow != null) { // Setup the video window hr = this.videoWindow.put_Owner(this.source.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(DirectShowLib.WindowStyle.Child | DirectShowLib.WindowStyle.ClipSiblings | DirectShowLib.WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); } MoveVideoWindow(); } else { if (VHost != null) { VHost.Dispose(); VHost = null; VHandle = IntPtr.Zero; VHostElement.Child = null; } } // Have the graph signal event via window callbacks for performance hr = this.mediaEventEx.SetNotifyWindow(this.source.Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); this.Focus(); // Run the graph to play the media file hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); this.currentState = PlayState.Running; SetPauseIcon(); double duration = 0.0; hr = mediaPosition.get_Duration(out duration); DsError.ThrowExceptionForHR(hr); slider_pos.Maximum = duration; //Запускаем таймер обновления позиции if (timer != null) timer.Start(); }
private void ConfigureEVR() { baseFilter = (IBaseFilter)new EnhancedVideoRenderer(); IEVRFilterConfig filterConfig = (IEVRFilterConfig)baseFilter; filterConfig.SetNumberOfStreams(1); object o; ((IMFGetService)baseFilter).GetService(MR_VIDEO_RENDER_SERVICE, IID_IMFVideoDisplayControl, out o); EVRCtrl = (IMFVideoDisplayControl)o; EVRCtrl.SetVideoWindow(winHandle); EVRCtrl.SetAspectRatioMode(1); Form1_ResizeMove(null, null); graphBuilder.AddFilter(baseFilter, "Enhanced Video Renderer"); }
private void PlayMovieInWindow() { int hr = 0; this.graphBuilder = (IGraphBuilder)new FilterGraph(); //Добавляем в граф нужный рендерер (Auto - graphBuilder сам выберет рендерер) Settings.VRenderers renderer = Settings.VideoRenderer; if (renderer == Settings.VRenderers.Overlay) { IBaseFilter add_vr = (IBaseFilter)new VideoRenderer(); hr = graphBuilder.AddFilter(add_vr, "Video Renderer"); DsError.ThrowExceptionForHR(hr); } else if (renderer == Settings.VRenderers.VMR7) { IBaseFilter add_vmr = (IBaseFilter)new VideoMixingRenderer(); hr = graphBuilder.AddFilter(add_vmr, "Video Renderer"); DsError.ThrowExceptionForHR(hr); } else if (renderer == Settings.VRenderers.VMR9) { IBaseFilter add_vmr9 = (IBaseFilter)new VideoMixingRenderer9(); hr = graphBuilder.AddFilter(add_vmr9, "Video Mixing Renderer 9"); DsError.ThrowExceptionForHR(hr); } else if (renderer == Settings.VRenderers.EVR) { //Создаём Win32-окно, т.к. использовать WPF-поверхность не получится VHost = new VideoHwndHost(); VHost.RepaintRequired += new EventHandler(VHost_RepaintRequired); VHostElement.Visibility = Visibility.Visible; VHostElement.Child = VHost; VHandle = VHost.Handle; //Добавляем и настраиваем EVR IBaseFilter add_evr = (IBaseFilter)new EnhancedVideoRenderer(); hr = graphBuilder.AddFilter(add_evr, "Enhanced Video Renderer"); DsError.ThrowExceptionForHR(hr); object obj; IMFGetService pGetService = null; pGetService = (IMFGetService)add_evr; hr = pGetService.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out obj); MFError.ThrowExceptionForHR(hr); try { EVRControl = (IMFVideoDisplayControl)obj; } catch { Marshal.ReleaseComObject(obj); throw; } //Указываем поверхность hr = EVRControl.SetVideoWindow(VHandle); MFError.ThrowExceptionForHR(hr); //Сохраняем аспект hr = EVRControl.SetAspectRatioMode(MFVideoAspectRatioMode.PreservePicture); MFError.ThrowExceptionForHR(hr); } // Have the graph builder construct its the appropriate graph automatically hr = this.graphBuilder.RenderFile(this.filepath, null); DsError.ThrowExceptionForHR(hr); if (EVRControl == null) { //Ищем рендерер и ВКЛЮЧАЕМ соблюдение аспекта (рендерер сам подгонит картинку под размер окна, с учетом аспекта) IsRendererARFixed = false; IBaseFilter filter = null; graphBuilder.FindFilterByName("Video Renderer", out filter); if (filter != null) { IVMRAspectRatioControl vmr = filter as IVMRAspectRatioControl; if (vmr != null) { DsError.ThrowExceptionForHR(vmr.SetAspectRatioMode(VMRAspectRatioMode.LetterBox)); IsRendererARFixed = true; } } else { graphBuilder.FindFilterByName("Video Mixing Renderer 9", out filter); if (filter != null) { IVMRAspectRatioControl9 vmr9 = filter as IVMRAspectRatioControl9; if (vmr9 != null) { DsError.ThrowExceptionForHR(vmr9.SetAspectRatioMode(VMRAspectRatioMode.LetterBox)); IsRendererARFixed = true; } } } } else IsRendererARFixed = true; this.mediaControl = (IMediaControl)this.graphBuilder; this.mediaEventEx = (IMediaEventEx)this.graphBuilder; this.mediaSeeking = (IMediaSeeking)this.graphBuilder; this.mediaPosition = (IMediaPosition)this.graphBuilder; this.videoWindow = (EVRControl == null) ? this.graphBuilder as IVideoWindow : null; this.basicVideo = (EVRControl == null) ? this.graphBuilder as IBasicVideo : null; this.basicAudio = this.graphBuilder as IBasicAudio; this.basicAudio.put_Volume(VolumeSet); this.CheckIsAudioOnly(); if (!this.isAudioOnly) { if (videoWindow != null) { hr = this.videoWindow.put_Owner(this.source.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_MessageDrain(this.source.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(DirectShowLib.WindowStyle.Child | DirectShowLib.WindowStyle.ClipSiblings | DirectShowLib.WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); } this.MoveVideoWindow(); } else { if (VHost != null) { VHost.Dispose(); VHost = null; VHandle = IntPtr.Zero; VHostElement.Child = null; VHostElement.Visibility = Visibility.Collapsed; } } hr = this.mediaEventEx.SetNotifyWindow(this.source.Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); //Восстанавливаем старую позицию if (mediaload == MediaLoad.Update && oldpos != TimeSpan.Zero) { if (NaturalDuration >= oldpos) { hr = mediaPosition.put_CurrentPosition(oldpos.TotalSeconds); DsError.ThrowExceptionForHR(hr); } } //Восстанавливаем старый PlayState if (mediaload == MediaLoad.Update && (oldplaystate == PlayState.Paused || oldplaystate == PlayState.Stopped)) { hr = this.mediaControl.Pause(); DsError.ThrowExceptionForHR(hr); this.currentState = PlayState.Paused; this.SetPlayIcon(); } else { hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); this.currentState = PlayState.Running; this.SetPauseIcon(); } AddFiltersToMenu(); }
private void InitializeEvr(DirectShowLib.IBaseFilter pEvr, int dwStreams, string forcedVideoRenderer) { int hr = 0; var pGetService = pEvr as IMFGetService; IMFVideoDisplayControl pDisplay; // Continue with the rest of the set-up. //try to load the custom presenter IMFVideoPresenter pPresenter = null; if (_config.VideoConfig.EnableCustomPresenter && !string.Equals(forcedVideoRenderer, "evr", StringComparison.OrdinalIgnoreCase)) { IMFVideoRenderer pRenderer = pEvr as IMFVideoRenderer; pPresenter = URCOMLoader.Instance.GetObject("EVR Presenter (babgvant)", false) as IMFVideoPresenter; try { if (pPresenter != null) { hr = pRenderer.InitializeRenderer(null, pPresenter); if (hr > -1) { _customEvrPresenterLoaded = true; IEVRCPConfig cp = pPresenter as IEVRCPConfig; if (cp != null) { hr = cp.SetInt(EVRCPSetting.NOMINAL_RANGE, _config.VideoConfig.NominalRange); DsError.ThrowExceptionForHR(hr); } } } } finally { if (pPresenter != null) Marshal.ReleaseComObject(pPresenter); } } // Set the video window. object o; hr = pGetService.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o); DsError.ThrowExceptionForHR(hr); try { pDisplay = (IMFVideoDisplayControl)o; } catch { Marshal.ReleaseComObject(o); throw; } // Set the number of streams. hr = pDisplay.SetVideoWindow(VideoWindowHandle); DsError.ThrowExceptionForHR(hr); IEVRFilterConfig evrConfig = pEvr as IEVRFilterConfig; int pdwMaxStreams; if (evrConfig != null) { hr = evrConfig.GetNumberOfStreams(out pdwMaxStreams); DsError.ThrowExceptionForHR(hr); _logger.Debug("NumberOfStreams: {0}", pdwMaxStreams); if (pdwMaxStreams < dwStreams) { hr = evrConfig.SetNumberOfStreams(dwStreams); DsError.ThrowExceptionForHR(hr); _logger.Debug("Set NumberOfStreams: {0}", dwStreams); } } else _logger.Error("Couldn't get IEVRFilterConfig from EVR"); // Return the IMFVideoDisplayControl pointer to the caller. _mPDisplay = pDisplay; }
private void InitializeEVR(IBaseFilter pEVR, int dwStreams, out IMFVideoDisplayControl ppDisplay) { IMFVideoRenderer pRenderer; IMFVideoDisplayControl pDisplay; IEVRFilterConfig pConfig; IMFVideoPresenter pPresenter; // Before doing anything else, set any custom presenter or mixer. // Presenter? if (m_clsidPresenter != Guid.Empty) { Type type = Type.GetTypeFromCLSID(m_clsidPresenter); // An error here means that the custom presenter sample from // http://mfnet.sourceforge.net hasn't been installed or // registered. pPresenter = (IMFVideoPresenter)Activator.CreateInstance(type); try { pRenderer = (IMFVideoRenderer)pEVR; pRenderer.InitializeRenderer(null, pPresenter); } finally { //Marshal.ReleaseComObject(pPresenter); } } // Continue with the rest of the set-up. // Set the video window. object o; IMFGetService pGetService = null; pGetService = (IMFGetService)pEVR; pGetService.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o); try { pDisplay = (IMFVideoDisplayControl)o; } catch { Marshal.ReleaseComObject(o); throw; } try { // Set the number of streams. pDisplay.SetVideoWindow(m_hwndVideo.Handle); if (dwStreams > 1) { pConfig = (IEVRFilterConfig)pEVR; pConfig.SetNumberOfStreams(dwStreams); } // Set the display position to the entire window. Rectangle r = m_hwndVideo.ClientRectangle; MFRect rc = new MFRect(r.Left, r.Top, r.Right, r.Bottom); pDisplay.SetVideoPosition(null, rc); // Return the IMFVideoDisplayControl pointer to the caller. ppDisplay = pDisplay; } finally { //Marshal.ReleaseComObject(pDisplay); } m_pMixer = null; }
private void PlayMovieInWindow(string filename) { fps = 0; int hr = 0; this.graphBuilder = (IGraphBuilder)new FilterGraph(); //Добавляем в граф нужный рендерер (Auto - graphBuilder сам выберет рендерер) Settings.VRenderers renderer = Settings.VideoRenderer; if (renderer == Settings.VRenderers.Overlay) { IBaseFilter add_vr = (IBaseFilter)new VideoRenderer(); hr = graphBuilder.AddFilter(add_vr, "Video Renderer"); DsError.ThrowExceptionForHR(hr); } else if (renderer == Settings.VRenderers.VMR7) { IBaseFilter add_vmr = (IBaseFilter)new VideoMixingRenderer(); hr = graphBuilder.AddFilter(add_vmr, "Video Renderer"); DsError.ThrowExceptionForHR(hr); } else if (renderer == Settings.VRenderers.VMR9) { IBaseFilter add_vmr9 = (IBaseFilter)new VideoMixingRenderer9(); hr = graphBuilder.AddFilter(add_vmr9, "Video Mixing Renderer 9"); DsError.ThrowExceptionForHR(hr); } else if (renderer == Settings.VRenderers.EVR) { //Создаём Win32-окно, т.к. использовать WPF-поверхность не получится VHost = new VideoHwndHost(); VHost.RepaintRequired += new EventHandler(VHost_RepaintRequired); VHostElement.Visibility = Visibility.Visible; VHostElement.Child = VHost; VHandle = VHost.Handle; //Добавляем и настраиваем EVR IBaseFilter add_evr = (IBaseFilter)new EnhancedVideoRenderer(); hr = graphBuilder.AddFilter(add_evr, "Enhanced Video Renderer"); DsError.ThrowExceptionForHR(hr); object obj; IMFGetService pGetService = null; pGetService = (IMFGetService)add_evr; hr = pGetService.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out obj); MFError.ThrowExceptionForHR(hr); try { EVRControl = (IMFVideoDisplayControl)obj; } catch { Marshal.ReleaseComObject(obj); throw; } //Указываем поверхность hr = EVRControl.SetVideoWindow(VHandle); MFError.ThrowExceptionForHR(hr); //Отключаем сохранение аспекта hr = EVRControl.SetAspectRatioMode(MFVideoAspectRatioMode.None); MFError.ThrowExceptionForHR(hr); } // Have the graph builder construct its the appropriate graph automatically hr = this.graphBuilder.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); if (EVRControl == null) { //Ищем рендерер и отключаем соблюдение аспекта (аспект будет определяться размерами видео-окна) IBaseFilter filter = null; graphBuilder.FindFilterByName("Video Renderer", out filter); if (filter != null) { IVMRAspectRatioControl vmr = filter as IVMRAspectRatioControl; if (vmr != null) DsError.ThrowExceptionForHR(vmr.SetAspectRatioMode(VMRAspectRatioMode.None)); } else { graphBuilder.FindFilterByName("Video Mixing Renderer 9", out filter); if (filter != null) { IVMRAspectRatioControl9 vmr9 = filter as IVMRAspectRatioControl9; if (vmr9 != null) DsError.ThrowExceptionForHR(vmr9.SetAspectRatioMode(VMRAspectRatioMode.None)); } } } // QueryInterface for DirectShow interfaces this.mediaControl = (IMediaControl)this.graphBuilder; this.mediaEventEx = (IMediaEventEx)this.graphBuilder; this.mediaSeeking = (IMediaSeeking)this.graphBuilder; this.mediaPosition = (IMediaPosition)this.graphBuilder; // Query for video interfaces, which may not be relevant for audio files this.videoWindow = (EVRControl == null) ? this.graphBuilder as IVideoWindow : null; this.basicVideo = (EVRControl == null) ? this.graphBuilder as IBasicVideo : null; // Query for audio interfaces, which may not be relevant for video-only files this.basicAudio = this.graphBuilder as IBasicAudio; basicAudio.put_Volume(VolumeSet); //Ввод в ДиректШоу значения VolumeSet для установки громкости // Is this an audio-only file (no video component)? CheckIsAudioOnly(); if (!this.IsAudioOnly) { if (videoWindow != null) { // Setup the video window hr = this.videoWindow.put_Owner(this.source.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_MessageDrain(this.source.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(DirectShowLib.WindowStyle.Child | DirectShowLib.WindowStyle.ClipSiblings | DirectShowLib.WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); //Определяем fps double AvgTimePerFrame; hr = basicVideo.get_AvgTimePerFrame(out AvgTimePerFrame); DsError.ThrowExceptionForHR(hr); fps = (1.0 / AvgTimePerFrame); } else if (EVRControl != null) { //Определяем fps DetermineEVRFPS(); } //Ловим ошибку Ависинта IsAviSynthError = false; if (NaturalDuration.TotalMilliseconds == 10000.0) { //Признаки ошибки: duration=10000.0 и fps=24 (округлённо) if ((int)fps == 24 || fps == 0) IsAviSynthError = true; } MoveVideoWindow(); } else { if (VHost != null) { VHost.Dispose(); VHost = null; VHandle = IntPtr.Zero; VHostElement.Child = null; VHostElement.Visibility = Visibility.Collapsed; VHostElement.Width = VHostElement.Height = 0; VHostElement.Margin = new Thickness(0); } //Ловим ошибку Ависинта 2 (когда нет видео окна) IsAviSynthError = (NaturalDuration.TotalMilliseconds == 10000.0); if (m.isvideo) { //Видео должно было быть.. PreviewError("NO VIDEO", Brushes.Gainsboro); } } //Если выше не удалось определить fps - берём значение из массива if (fps == 0) fps = Calculate.ConvertStringToDouble(m.outframerate); // Have the graph signal event via window callbacks for performance hr = this.mediaEventEx.SetNotifyWindow(this.source.Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); if (mediaload == MediaLoad.update) //Перенесено из HandleGraphEvent, теперь позиция устанавливается до начала воспроизведения, т.е. за один заход, а не за два { if (NaturalDuration >= oldpos) //Позиционируем только если нужная позиция укладывается в допустимый диапазон mediaPosition.put_CurrentPosition(oldpos.TotalSeconds); //else // mediaPosition.put_CurrentPosition(NaturalDuration.TotalSeconds); //Ограничиваем позицию длиной клипа } // Run the graph to play the media file if (currentState == PlayState.Running) { //Продолжение воспроизведения, если статус до обновления был Running DsError.ThrowExceptionForHR(this.mediaControl.Run()); SetPauseIcon(); } else { //Запуск с паузы, если была пауза или это новое открытие файла DsError.ThrowExceptionForHR(this.mediaControl.Pause()); this.currentState = PlayState.Paused; SetPlayIcon(); } }
public void SetRendererInterfaces(IVMRWindowlessControl VMRWindowlessControl, IVMRWindowlessControl9 VMRWindowlessControl9, IMFVideoDisplayControl MFVideoDisplayControl) { _manager.SetRunning(true, VMRWindowlessControl, VMRWindowlessControl9, MFVideoDisplayControl); }
private void RenderStreams(IBaseFilter pSource) { int hr; bool bRenderedAudio = false; bool bRenderedVideo = false; IBaseFilter pEVR = (IBaseFilter) new EnhancedVideoRenderer(); IBaseFilter pAudioRenderer = (IBaseFilter) new DSoundRender(); try { // Add the EVR to the graph. hr = m_pGraph.AddFilter(pEVR, "EVR"); DsError.ThrowExceptionForHR(hr); InitializeEVR(pEVR, 1, out m_pDisplay); // Add the DSound Renderer to the graph. hr = m_pGraph.AddFilter(pAudioRenderer, "Audio Renderer"); DsError.ThrowExceptionForHR(hr); ICaptureGraphBuilder2 cgb; cgb = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); try { hr = cgb.SetFiltergraph(m_pGraph); DsError.ThrowExceptionForHR(hr); // Connect the streams. hr = cgb.RenderStream(null, MediaType.Video, pSource, null, pEVR); DsError.ThrowExceptionForHR(hr); hr = cgb.RenderStream(null, MediaType.Audio, pSource, null, pAudioRenderer); DsError.ThrowExceptionForHR(hr); // If we are using a splitter, the two lines above did nothing. We // ignore the errors from the next 2 statements in case the 2 lines above // *did* do something. hr = cgb.RenderStream(null, null, pSource, null, pEVR); //DsError.ThrowExceptionForHR(hr); hr = cgb.RenderStream(null, null, pSource, null, pAudioRenderer); //DsError.ThrowExceptionForHR(hr); IPin pPin = DsFindPin.ByConnectionStatus(pEVR, PinConnectedStatus.Unconnected, 0); if (pPin == null) { bRenderedVideo = true; } else { Marshal.ReleaseComObject(pPin); } pPin = DsFindPin.ByConnectionStatus(pAudioRenderer, PinConnectedStatus.Unconnected, 0); if (pPin == null) { bRenderedAudio = true; } else { Marshal.ReleaseComObject(pPin); } } finally { Marshal.ReleaseComObject(cgb); } // Remove un-used renderers. if (!bRenderedVideo) { m_pGraph.RemoveFilter(pEVR); // If we removed the EVR, then we also need to release our // pointer to the EVR display interfaace //Marshal.ReleaseComObject(m_pDisplay); m_pDisplay = null; } else { // EVR is still in the graph. Cache the interface pointer. Debug.Assert(pEVR != null); m_pEVR = pEVR; } if (!bRenderedAudio) { m_pGraph.RemoveFilter(pAudioRenderer); } } finally { Marshal.ReleaseComObject(pAudioRenderer); } }
private void SetupEvrDisplay() { int hr=0; //Guid presenterCLSID = new Guid(0xeb449d36, 0x4, 0x4ea8, 0x90, 0x74, 0x40, 0xc5, 0xf4, 0x94, 0xb5, 0xe4); //Guid presenterCLSID = new Guid(0x9707fc9c, 0x807b, 0x41e3, 0x98, 0xa8, 0x75, 0x17, 0x6f, 0x95, 0xa0, 0x62); //Guid presenterCLSID = new Guid("29FAB022-F7CC-4819-B2B8-D9B6BCFB6698"); IMFGetService mfgs = evrRenderer as IMFGetService; if (mfgs != null) { IMFVideoPresenter pPresenter = null; try { if (ps.CustomPresenterEnabled) { Guid presenterCLSID = new Guid(ps.CustomPresenter); IMFVideoRenderer pRenderer = evrRenderer as IMFVideoRenderer; Type type = Type.GetTypeFromCLSID(presenterCLSID); pPresenter = (IMFVideoPresenter)Activator.CreateInstance(type); if (pPresenter != null) { try { pRenderer.InitializeRenderer(null, pPresenter); cpsett = pPresenter as IEVRCPConfig; if (cpsett != null) { int range; float alpha; bool mftime; hr = cpsett.GetInt(EVRCPSetting.NOMINAL_RANGE, out range); hr = cpsett.SetInt(EVRCPSetting.NOMINAL_RANGE, range); hr = cpsett.GetFloat(EVRCPSetting.SUBTITLE_ALPHA, out alpha); hr = cpsett.SetFloat(EVRCPSetting.SUBTITLE_ALPHA, alpha); hr = cpsett.GetBool(EVRCPSetting.USE_MF_TIME_CALC, out mftime); hr = cpsett.SetBool(EVRCPSetting.USE_MF_TIME_CALC, mftime); hr = cpsett.GetInt(EVRCPSetting.FRAME_DROP_THRESHOLD, out range); hr = cpsett.SetInt(EVRCPSetting.FRAME_DROP_THRESHOLD, range+1); hr = cpsett.GetBool(EVRCPSetting.EVRCP_SETTING_REQUEST_OVERLAY, out mftime); hr = cpsett.SetBool(EVRCPSetting.EVRCP_SETTING_REQUEST_OVERLAY, false); } } finally { if (pPresenter != null && cpsett == null) Marshal.ReleaseComObject(pPresenter); } } } //object objStateSink = null; //mfgs.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, // typeof(IMFClockStateSink).GUID, // out objStateSink); //stateSink = objStateSink as IMFClockStateSink; //object objRateSupp= null; //mfgs.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, // typeof(IMFRateSupport).GUID, // out objRateSupp); //rateSupport = objRateSupp as IMFRateSupport; object objMixBmp = null; mfgs.GetService(MFServices.MR_VIDEO_MIXER_SERVICE, typeof(IMFVideoMixerBitmap).GUID, out objMixBmp); mixBmp = objMixBmp as IMFVideoMixerBitmap; object objDisplay = null; mfgs.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out objDisplay ); FileLogger.Log("PlayMovieInWindow: MR_VIDEO_RENDER_SERVICE"); evrDisplay = objDisplay as IMFVideoDisplayControl; this.evrDisplay.SetVideoWindow(this.Handle); MediaFoundation.Misc.MFSize videoSize = new MediaFoundation.Misc.MFSize(); MediaFoundation.Misc.MFSize ar = new MediaFoundation.Misc.MFSize(); //evrDisplay.GetNativeVideoSize(videoSize, ar); if ((videoSize.cx == 0 && videoSize.cy == 0) || videoSize.cx <= 0) { IEVRFilterConfig evrConfig = evrRenderer as IEVRFilterConfig; int pdwMaxStreams; evrConfig.GetNumberOfStreams(out pdwMaxStreams); FileLogger.Log("NumberOfStreams: {0}", pdwMaxStreams); if (pdwMaxStreams < 1) { evrConfig.SetNumberOfStreams(1); FileLogger.Log("Set NumberOfStreams: {0}", 1); } } //object objMemConfig = null; //mfgs.GetService(MFServices.MR_VIDEO_ACCELERATION_SERVICE, typeof(IDirectXVideoMemoryConfiguration).GUID, out objMemConfig); } catch (InvalidCastException) { //do nothing } } }
protected void CloseSession() { if (m_pVideoDisplay != null) { Marshal.ReleaseComObject(m_pVideoDisplay); m_pVideoDisplay = null; } if (m_pSession != null) { m_pSession.Close(); // Wait for the close operation to complete bool res = m_hCloseEvent.WaitOne(5000, true); if (!res) { TRACE(("WaitForSingleObject timed out!")); } } // Complete shutdown operations // 1. Shut down the media source if (m_pSource != null) { m_pSource.Shutdown(); SafeRelease(m_pSource); m_pSource = null; } // 2. Shut down the media session. (Synchronous operation, no events.) if (m_pSession != null) { m_pSession.Shutdown(); Marshal.ReleaseComObject(m_pSession); m_pSession = null; } }
private void InitializeEvr(DirectShowLib.IBaseFilter pEvr, int dwStreams) { int hr = 0; var pGetService = pEvr as IMFGetService; IMFVideoDisplayControl pDisplay; // Continue with the rest of the set-up. //try to load the custom presenter IMFVideoPresenter pPresenter = null; if (_mbtConfig.Configuration.InternalPlayerConfiguration.VideoConfig.UseCustomPresenter) { IMFVideoRenderer pRenderer = pEvr as IMFVideoRenderer; pPresenter = _urCom.GetObject("EVR Presenter (babgvant)", false) as IMFVideoPresenter; try { if (pPresenter != null) { hr = pRenderer.InitializeRenderer(null, pPresenter); if (hr > -1) _customEvrPresenterLoaded = true; } } finally { if(pPresenter != null) Marshal.ReleaseComObject(pPresenter); } } // Set the video window. object o; hr = pGetService.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o); DsError.ThrowExceptionForHR(hr); try { pDisplay = (IMFVideoDisplayControl)o; } catch { Marshal.ReleaseComObject(o); throw; } // Set the number of streams. hr = pDisplay.SetVideoWindow(VideoWindowHandle); DsError.ThrowExceptionForHR(hr); IEVRFilterConfig evrConfig = pEvr as IEVRFilterConfig; int pdwMaxStreams; if (evrConfig != null) { hr = evrConfig.GetNumberOfStreams(out pdwMaxStreams); DsError.ThrowExceptionForHR(hr); _logger.Debug("NumberOfStreams: {0}", pdwMaxStreams); if (pdwMaxStreams < dwStreams) { hr = evrConfig.SetNumberOfStreams(dwStreams); DsError.ThrowExceptionForHR(hr); _logger.Debug("Set NumberOfStreams: {0}", dwStreams); } } else _logger.Error("Couldn't get IEVRFilterConfig from EVR"); // Return the IMFVideoDisplayControl pointer to the caller. _mPDisplay = pDisplay; }
private void CloseInterfaces() { int hr = 0; try { lock (this) { // Relinquish ownership (IMPORTANT!) after hiding video window //if (!this.isAudioOnly) //{ // hr = this.videoWindow.put_Visible(OABool.False); // DsError.ThrowExceptionForHR(hr); // hr = this.videoWindow.put_Owner(IntPtr.Zero); // DsError.ThrowExceptionForHR(hr); //} //#if DEBUG try { if (rot != null) { rot.Dispose(); rot = null; } } catch { } //#endif if (dvdSubtitle != null) Marshal.ReleaseComObject(dvdSubtitle); dvdSubtitle = null; if (dvdCtrl != null) { hr = dvdCtrl.SetOption(DvdOptionFlag.ResetOnStop, true); } if (cmdOption != null) { Marshal.ReleaseComObject(cmdOption); cmdOption = null; } pendingCmd = false; dvdCtrl = null; if (dvdInfo != null) { Marshal.ReleaseComObject(dvdInfo); dvdInfo = null; } if (this.mediaEventEx != null) { if (dvdGraph != null) hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, WM.DVD_EVENT, IntPtr.Zero); else hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, WM.NULL, IntPtr.Zero); //DsError.ThrowExceptionForHR(hr); } if (evrDisplay != null) { //evrDisplay.SetVideoWindow(IntPtr.Zero); Marshal.ReleaseComObject(evrDisplay); } evrDisplay = null; if (this.evrRenderer != null) Marshal.ReleaseComObject(evrRenderer); evrRenderer = null; // Release and zero DirectShow interfaces if (this.mediaEventEx != null) this.mediaEventEx = null; if (this.mediaSeeking != null) this.mediaSeeking = null; if (this.mediaPosition != null) this.mediaPosition = null; if (this.mediaControl != null) this.mediaControl = null; if (this.basicAudio != null) this.basicAudio = null; if (this.basicVideo != null) this.basicVideo = null; //if (this.videoWindow != null) // this.videoWindow = null; if (this.frameStep != null) this.frameStep = null; if (this.graphBuilder != null) Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null; if (this.dvdGraph != null) Marshal.ReleaseComObject(dvdGraph); dvdGraph = null; GC.Collect(); } } catch { } }
public int InitializeMedia(string MediaFile, int dwrate, float dwvolume, bool IsFullScreen) { int hr; MFStartup(MF_VERSION, MFSTARTUP_FULL); MFCreateMediaSession(IntPtr.Zero, out mediaSession); MFCreateTopology(out IMFTopology topo); MFCreateSourceResolver(out IMFSourceResolver resolver); IUnknown unknown; try { resolver.CreateObjectFromURL(MediaFile, MF_RESOLUTION_MEDIASOURCE | MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE, null, out uint objtype, out unknown); } catch { MessageBox.Show("不支持的媒体格式。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return(0); } IMFMediaSource source = unknown as IMFMediaSource; source.CreatePresentationDescriptor(out IMFPresentationDescriptor descriptor); if (MFRequireProtectedEnvironment(descriptor) == 0) { MessageBox.Show("媒体受保护,无法播放。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return(0); } descriptor.GetStreamDescriptorCount(out uint sdcount); for (uint i = 0; i < sdcount; i++) { descriptor.GetStreamDescriptorByIndex(i, out bool IsSelected, out IMFStreamDescriptor sd); if (!IsSelected) { descriptor.SelectStream(i); } sd.GetMediaTypeHandler(out IMFMediaTypeHandler typeHandler); typeHandler.GetMajorType(out Guid streamtype); IMFActivate renderer; if (streamtype == MFMediaType_Audio) { hr = MFCreateAudioRendererActivate(out renderer); } else if (streamtype == MFMediaType_Video) { hr = MFCreateVideoRendererActivate(VideoWnd.Handle, out renderer); HasVideo = true; } else { MessageBox.Show("不支持的媒体格式。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return(0); } hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, out IMFTopologyNode sourcenode); sourcenode.SetUnknown(MF_TOPONODE_SOURCE, source as IUnknown); sourcenode.SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, descriptor as IUnknown); sourcenode.SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, sd as IUnknown); topo.AddNode(sourcenode); MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, out IMFTopologyNode outputnode); outputnode.SetObject(renderer as IUnknown); topo.AddNode(outputnode); outputnode.SetUINT32(MF_TOPONODE_NOSHUTDOWN_ON_REMOVE, 0); hr = sourcenode.ConnectOutput(0, outputnode, 0); } mediaSession.SetTopology(0, topo); Rate = dwrate; Volume = dwvolume; this.IsFullScreen = IsFullScreen; uint eventtype = 0; while (eventtype != MESessionTopologyStatus) { mediaSession.GetEvent(0, out IMFMediaEvent mediaevent); mediaevent.GetType(out eventtype); mediaevent = null; } Guid guid_ratecontrol = typeof(IMFRateControl).GUID; MFGetService(mediaSession as IUnknown, ref MF_RATE_CONTROL_SERVICE, ref guid_ratecontrol, out IUnknown _ratecontrol); IMFRateControl ratecontrol = _ratecontrol as IMFRateControl; hr = ratecontrol.SetRate(false, Rate >= 0 ? Rate * 7 / 10 + 1 : 1 / (1 + Rate / -10 * 7)); try { Guid guid_volume = typeof(IMFStreamAudioVolume).GUID; Guid guid_audiopolicy = typeof(IMFAudioPolicy).GUID; hr = MFGetService(mediaSession as IUnknown, ref MR_STREAM_VOLUME_SERVICE, ref guid_volume, out IUnknown _volume); hr = MFGetService(mediaSession as IUnknown, ref MR_AUDIO_POLICY_SERVICE, ref guid_audiopolicy, out IUnknown _policy); IMFStreamAudioVolume volumecontrol = _volume as IMFStreamAudioVolume; IMFAudioPolicy policy = _policy as IMFAudioPolicy; volumecontrol.GetChannelCount(out uint channelcount); for (uint c = 0; c < channelcount; c++) { volumecontrol.SetChannelVolume(c, Volume); } policy.SetDisplayName(" "); } catch { } try { Guid guid_videocontrol = typeof(IMFVideoDisplayControl).GUID; hr = MFGetService(mediaSession as IUnknown, ref MR_VIDEO_RENDER_SERVICE, ref guid_videocontrol, out IUnknown _videocontrol); IMFVideoDisplayControl videocontrol = _videocontrol as IMFVideoDisplayControl; VideoWnd.videocontrol = videocontrol; if (IsFullScreen) { VideoWnd.Top = 0; VideoWnd.Left = 0; VideoWnd.Width = (int)System.Windows.SystemParameters.PrimaryScreenWidth; VideoWnd.Height = (int)System.Windows.SystemParameters.PrimaryScreenHeight; } Rectangle videopos = new Rectangle(0, 0, VideoWnd.Width, VideoWnd.Height); videocontrol.SetVideoPosition(null, ref videopos); } catch { } hr = mediaSession.BeginGetEvent((IMFAsyncCallback)this, null); return(1); }
private void RenderStreams(IBaseFilter pSource) { int hr; bool bRenderedAudio = false; bool bRenderedVideo = false; IBaseFilter pEVR = (IBaseFilter)new EnhancedVideoRenderer(); IBaseFilter pAudioRenderer = (IBaseFilter)new DSoundRender(); try { // Add the EVR to the graph. hr = m_pGraph.AddFilter(pEVR, "EVR"); DsError.ThrowExceptionForHR(hr); InitializeEVR(pEVR, 1, out m_pDisplay); // Add the DSound Renderer to the graph. hr = m_pGraph.AddFilter(pAudioRenderer, "Audio Renderer"); DsError.ThrowExceptionForHR(hr); ICaptureGraphBuilder2 cgb; cgb = (ICaptureGraphBuilder2)new CaptureGraphBuilder2(); try { hr = cgb.SetFiltergraph(m_pGraph); DsError.ThrowExceptionForHR(hr); // Connect the streams. hr = cgb.RenderStream(null, MediaType.Video, pSource, null, pEVR); DsError.ThrowExceptionForHR(hr); hr = cgb.RenderStream(null, MediaType.Audio, pSource, null, pAudioRenderer); DsError.ThrowExceptionForHR(hr); // If we are using a splitter, the two lines above did nothing. We // ignore the errors from the next 2 statements in case the 2 lines above // *did* do something. hr = cgb.RenderStream(null, null, pSource, null, pEVR); //DsError.ThrowExceptionForHR(hr); hr = cgb.RenderStream(null, null, pSource, null, pAudioRenderer); //DsError.ThrowExceptionForHR(hr); IPin pPin = DsFindPin.ByConnectionStatus(pEVR, PinConnectedStatus.Unconnected, 0); if (pPin == null) { bRenderedVideo = true; } else { Marshal.ReleaseComObject(pPin); } pPin = DsFindPin.ByConnectionStatus(pAudioRenderer, PinConnectedStatus.Unconnected, 0); if (pPin == null) { bRenderedAudio = true; } else { Marshal.ReleaseComObject(pPin); } } finally { Marshal.ReleaseComObject(cgb); } // Remove un-used renderers. if (!bRenderedVideo) { m_pGraph.RemoveFilter(pEVR); // If we removed the EVR, then we also need to release our // pointer to the EVR display interfaace //Marshal.ReleaseComObject(m_pDisplay); m_pDisplay = null; } else { // EVR is still in the graph. Cache the interface pointer. Debug.Assert(pEVR != null); m_pEVR = pEVR; } if (!bRenderedAudio) { m_pGraph.RemoveFilter(pAudioRenderer); } } finally { Marshal.ReleaseComObject(pAudioRenderer); } }
private void CloseInterfaces() { int hr; if (m_adecOut != null) { CleanUpInterface(m_adecOut); m_adecOut = null; } if (_defaultAudioRenderer != null) { m_graph.RemoveFilter(_defaultAudioRenderer as DirectShowLib.IBaseFilter); CleanUpInterface(_defaultAudioRenderer); _defaultAudioRenderer = null; } if (_reclockAudioRenderer != null) { m_graph.RemoveFilter(_reclockAudioRenderer as DirectShowLib.IBaseFilter); CleanUpInterface(_reclockAudioRenderer); _reclockAudioRenderer = null; } if (_wasapiAR != null) { m_graph.RemoveFilter(_wasapiAR as DirectShowLib.IBaseFilter); CleanUpInterface(_wasapiAR); _wasapiAR = null; } if (_lavaudio != null) { m_graph.RemoveFilter(_lavaudio as DirectShowLib.IBaseFilter); CleanUpInterface(_lavaudio); _lavaudio = null; } if (_xyVsFilter != null) { m_graph.RemoveFilter(_xyVsFilter as DirectShowLib.IBaseFilter); CleanUpInterface(_xyVsFilter); _xyVsFilter = null; } if (_xySubFilter != null) { m_graph.RemoveFilter(_xySubFilter as DirectShowLib.IBaseFilter); CleanUpInterface(_xySubFilter); _xySubFilter = null; } if (_lavvideo != null) { m_graph.RemoveFilter(_lavvideo as DirectShowLib.IBaseFilter); CleanUpInterface(_lavvideo); _lavvideo = null; } if (_madvr != null) { m_graph.RemoveFilter(_madvr as DirectShowLib.IBaseFilter); CleanUpInterface(_madvr); _madvr = null; } if (_videoWindow != null) { // Relinquish ownership (IMPORTANT!) after hiding video window hr = _videoWindow.put_Visible(OABool.False); hr = _videoWindow.put_Owner(IntPtr.Zero); } if (_mediaEventEx != null) { hr = _mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); //Marshal.ReleaseComObject(_mediaEventEx); //_mediaEventEx = null; } //if (_dvdNav != null) //{ // Marshal.ReleaseComObject(_dvdNav); // _dvdNav = null; //} /* //this will double release the source filter if (dvdInfo != null) { Marshal.ReleaseComObject(dvdInfo); dvdInfo = null; } if (_mDvdControl != null) { Marshal.ReleaseComObject(_mDvdControl); } */ _mDvdControl = null; CleanUpInterface(_mPDisplay); _mPDisplay = null; CleanUpInterface(_sourceFilter); _sourceFilter = null; CleanUpInterface(_mPEvr); _mPEvr = null; CleanUpInterface(m_filterGraph); m_filterGraph = null; m_filterGraph = null; _mediaEventEx = null; _mediaSeeking = null; _mediaPosition = null; _mediaControl = null; _basicAudio = null; _basicVideo = null; m_graph = null; _videoWindow = null; _filterGraph = null; if (m_dsRot != null) m_dsRot.Dispose(); m_dsRot = null; _mSeekCaps = 0; _streams = null; GC.Collect(); }
private void CloseInterfaces() { int hr = 0; try { lock (locker) { // Relinquish ownership (IMPORTANT!) after hiding video window if (!this.isAudioOnly && this.videoWindow != null) { hr = this.videoWindow.put_Visible(OABool.False); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_Owner(IntPtr.Zero); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_MessageDrain(IntPtr.Zero); DsError.ThrowExceptionForHR(hr); } if (EVRControl != null) { Marshal.ReleaseComObject(EVRControl); EVRControl = null; } if (this.mediaEventEx != null) { hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); this.mediaEventEx = null; } if (this.mediaSeeking != null) this.mediaSeeking = null; if (this.mediaPosition != null) this.mediaPosition = null; if (this.mediaControl != null) this.mediaControl = null; if (this.basicAudio != null) this.basicAudio = null; if (this.basicVideo != null) this.basicVideo = null; if (this.videoWindow != null) this.videoWindow = null; if (this.graphBuilder != null) { while (Marshal.ReleaseComObject(this.graphBuilder) > 0) ; this.graphBuilder = null; } GC.Collect(); } } catch (Exception ex) { System.Windows.MessageBox.Show("CloseInterfaces: " + ex.Message, Languages.Translate("Error"), MessageBoxButton.OK, MessageBoxImage.Error); } }
public void CloseInterfaces() { //mediaEvent = null; if (mediaControl != null) mediaControl.Stop(); if (baseFilter != null) { Marshal.ReleaseComObject(baseFilter); baseFilter = null; } EVRCtrl = null; VMRCtrl = null; if (dvdGraphBuilder != null) { Marshal.ReleaseComObject(dvdGraphBuilder); dvdGraphBuilder = null; } if (graphBuilder != null) { Marshal.ReleaseComObject(graphBuilder); graphBuilder = null; } mediaControl = null; }