protected int SetVideoWindow() { int hr; videoWindow = (IVideoWindow)m_graphBuilder; if (videoWindow == null) { return(0); } //Set the owener of the videoWindow to an IntPtr of some sort (the Handle of any control - could be a form / button etc.) hr = videoWindow.put_Owner(m_panel.Handle); DsError.ThrowExceptionForHR(hr); //Set the style of the video window hr = videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); hr = videoWindow.put_MessageDrain(m_panel.Handle); // Position video window in client rect of main application window hr = videoWindow.SetWindowPosition(0, 0, m_panel.Width, m_panel.Height); DsError.ThrowExceptionForHR(hr); // Make the video window visible hr = videoWindow.put_Visible(OABool.True); DsError.ThrowExceptionForHR(hr); return(hr); }
private bool PlayVideo(string path) { CleanUp(); FilterGraph = new FilgraphManager(); FilterGraph.RenderFile(path); BasicAudio = FilterGraph as IBasicAudio; try { VideoWindow = FilterGraph as IVideoWindow; VideoWindow.Owner = (int)panel1.Handle; VideoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN; VideoWindow.SetWindowPosition(panel1.ClientRectangle.Left, panel1.ClientRectangle.Top, panel1.ClientRectangle.Width, panel1.ClientRectangle.Height); } catch (Exception) { VideoWindow = null; return(false); } MediaEvent = FilterGraph as IMediaEvent; MediaEventEx = FilterGraph as IMediaEventEx; MediaPosition = FilterGraph as IMediaPosition; MediaControl = FilterGraph as IMediaControl; MediaControl.Run(); return(true); }
public Motor(AnaPencere anapencere) { this.anaPencere = anapencere; this.bulunmaDurumu = false; // bulunma durumu(çevrimiçi,meþgul vs.) ayarlanmadý this.kayitDurumu = RTC_REGISTRATION_STATE.RTCRS_NOT_REGISTERED; // Henüz kayýt olmadýk htPencereler = new Hashtable(); // uri key leri ile pencereler takip edilir Oturumlar = new ArrayList(); // açýlan oturumlarla(sessionEvent.Sessison) oturumlar takip edilir try { istemci = new RTCClientClass(); istemci.Initialize(); istemci.EventFilter = Sabitler.RTC_EVENTFILTERS; istemci.ListenForIncomingSessions = RTC_LISTEN_MODE.RTCLM_BOTH; // Gelen mesajlarý dinle, SIP portunu açar(5060) istemci.IRTCEventNotification_Event_Event += new IRTCEventNotification_EventEventHandler(istemci_IRTCEventNotification_Event_Event); istemci.SetPreferredMediaTypes(Sabitler.RTC_MEDIA_SABITLERI, true); gelenMedia = istemci.get_IVideoWindow(RTC_VIDEO_DEVICE.RTCVD_RECEIVE); gidenMedia = istemci.get_IVideoWindow(RTC_VIDEO_DEVICE.RTCVD_PREVIEW); istemci.ClientName = "RTCClient"; istemci.ClientCurVer = "1.0"; } catch(COMException hata) { this.anaPencere.MesajGoster(hata.ToString(), "Hata"); } }
public void Stop() { if (_parentControl != null) { _parentControl.SizeChanged -= _parentControl_SizeChanged; } if (_videoWin != null) { _videoWin.put_Visible(OABool.False); _videoWin = null; } if (_mediaCtrl != null) { _mediaCtrl.Stop(); _mediaCtrl = null; } if (_rotEntry != null) { _rotEntry.Dispose(); _rotEntry = null; } if (_graphBuilder != null) { DirectShowUtil.ReleaseComObject(_graphBuilder, 2000); _graphBuilder = null; } }
/// <summary> /// Disconnect and remove all filters except the device /// and compressor filters. This is the opposite of /// renderGraph(). Soem properties such as FrameRate /// can only be set when the device output pins are not /// connected. /// </summary> void DerenderGraph() { // Stop the graph if it is running (ignore errors) _mediaControl?.Stop(); // Free the preview window (ignore errors) if (_videoWindow != null) { _videoWindow.put_Visible(OABool.False); _videoWindow.put_Owner(IntPtr.Zero); _videoWindow = null; } if ((int)_actualGraphState < (int)GraphState.Rendered) { return; } // Update the state _actualGraphState = GraphState.Created; _isPreviewRendered = false; // Disconnect all filters downstream of the // video and audio devices. If we have a compressor // then disconnect it, but don't remove it if (_videoDeviceFilter != null) { RemoveDownstream(_videoDeviceFilter); } }
/// <summary> /// Configure the video window /// </summary> /// <param name="videoWindow">Interface of the video renderer</param> /// <param name="previewControl">Preview Control to draw into</param> private void ConfigureVideoWindow(IVideoWindow videoWindow, Control previewControl) { int hr; if (previewControl == null) { return; } // Set the output window hr = videoWindow.put_Owner(ThreadSafe.GetHandle(previewControl)); if (hr >= 0) // If there is video { // Set the window style hr = videoWindow.put_WindowStyle((WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings)); DsError.ThrowExceptionForHR(hr); // Make the window visible hr = videoWindow.put_Visible(OABool.True); DsError.ThrowExceptionForHR(hr); // Position the playing location Rectangle rc = ThreadSafe.GetClientRectangle(previewControl); hr = videoWindow.SetWindowPosition(0, 0, rc.Right, rc.Bottom); DsError.ThrowExceptionForHR(hr); } }
/// <summary> /// Dispose interface information /// </summary> private void disposeInterfaces() { m_graph = null; m_mediaControl = null; m_videoWindow = null; m_camControl = null; }
/// <summary> /// Called when a node or a connection is added/removed in the DaggerLib graph /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Graph_OnTopologyChanged(object sender, EventArgs e) { // the topology of the graph has changed // see if seeking is available and set the extent of the TimeSliderControl _mediaSeeking = _graph as IMediaSeeking; if (_mediaSeeking != null) { long duration = 0; _mediaSeeking.GetDuration(out duration); // only set the extents if something has changed if (_timeSliderControl.Extent != (int)(duration / 10000)) { _timeSliderControl.Extent = (int)(duration / 10000); _timeSliderControl.Min = 0; _timeSliderControl.Max = _timeSliderControl.Extent; } } // see if frame step is available _frameStepButton.Enabled = GetFrameStepInterface(); // see if IVideoWindow is available _videoWindow = _graph as IVideoWindow; }
public PlayerCore(string file) { graphBuilder = (new FilterGraph()) as IFilterGraph2; if (graphBuilder == null) return; mediaControl = graphBuilder as IMediaControl; mediaSeeking = graphBuilder as IMediaSeeking; audioControl = graphBuilder as IBasicAudio; if (mediaControl == null || mediaSeeking == null || audioControl == null) return; //int hr = mediaControl.RenderFile(file); FileInfo info = new FileInfo(file); ISupport support = Supports.Instance[info.Extension]; int hr = -1; if (support != null) hr = support.RenderGraph(graphBuilder, file); else hr = mediaControl.RenderFile(file); fileName = file; if (hr != 0) errorStack.Push(hr); if (hr != 0) return; mediaSeeking.SetTimeFormat(TimeFormat.MediaTime); isValidate = true; window = graphBuilder as IVideoWindow; if (window != null) { int width = 0; int height = 0; window.get_Width(out width); window.get_Height(out height); nativeSize = new Size(width, height); } }
// Set the video window within the control specified by hControl private void ConfigVideoWindow(Control hControl) { int hr; IVideoWindow ivw = m_FilterGraph as IVideoWindow; // Set the parent try { hr = ivw.put_Owner(hControl.Handle); } catch { } //DsError.ThrowExceptionForHR( hr ); // Turn off captions, etc hr = ivw.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings); //DsError.ThrowExceptionForHR( hr ); // Yes, make it visible hr = ivw.put_Visible(OABool.False); //DsError.ThrowExceptionForHR( hr ); // Move to upper left corner //Rectangle rc = hControl.ClientRectangle; //hr = ivw.SetWindowPosition( 0, 0, rc.Right, rc.Bottom ); //DsError.ThrowExceptionForHR( hr ); }
protected void derenderGraph() { if (this.mediaControl != null) { this.mediaControl.Stop(); } if (this.videoWindow != null) { this.videoWindow.put_Visible(0); this.videoWindow.put_Owner(IntPtr.Zero); this.videoWindow = null; } if (this.PreviewWindow != null) { this.previewWindow.Resize -= new EventHandler(this.onPreviewWindowResize); } if (this.graphState >= GraphState.Rendered) { this.graphState = GraphState.Created; this.isCaptureRendered = false; this.isPreviewRendered = false; this.muxFilter = null; this.baseGrabFlt = null; } }
/// <summary> /// Show/hide the video window. /// </summary> /// <param name="mute"></param> /// <returns></returns> public bool SetVisible(bool visible) { if (this.visible == visible) { return(true); } this.visible = visible; try { IVideoWindow ivw = (IVideoWindow)fgm; if (visible) { ivw.Visible = VISIBLE; } else { ivw.Visible = INVISIBLE; } } catch (Exception e) { eventLog.WriteEntry("Failed to set video visibility: " + e.ToString(), EventLogEntryType.Error, 1001); Debug.WriteLine("Failed to set video visibility: " + e.ToString()); return(false); } return(true); }
public void Initialize() { _graphBuilder = (IGraphBuilder) new FilterGraph(); _filterCamera = new DSFilter(new VirtualCamFilter()); _graphBuilder.AddFilter(_filterCamera.Value, "Virtual Camera"); //_filterCamera.Pins[0].Direction = PinDirection. //_filterVMR9Renderer = new DSFilter(new Guid("51B4ABF3-748F-4E3B-A276-C828330E926A")); //_graphBuilder.AddFilter(_filterVMR9Renderer.Value, "Renderer"); _filterYUV = new DSFilter(new Guid("B179A682-641B-11D2-A4D9-0060080BA634")); _graphBuilder.AddFilter(_filterYUV.Value, "YUV"); //_filterH264Encoder = new DSFilter(new Guid("3FD83588-D403-40A2-9739-5F75E1590AB8")); _filterH264Encoder = new DSFilter(new H264EncoderFilter()); _graphBuilder.AddFilter(_filterH264Encoder.Value, "H264 En"); //_filterNullRenderer = new DSFilter(new Guid("C1F400A4-3F08-11D3-9F0B-006008039E37")); //_graphBuilder.AddFilter(_filterNullRenderer.Value, "Null"); _filterRTSPServer = new DSFilter(new Guid("EABF2C99-F9AD-43CD-8108-109D4E9FADC5")); _graphBuilder.AddFilter(_filterRTSPServer.Value, "RTSP Server"); // Camera -> RGB2YUV -> H264 -> RTSP _filterCamera.OutputPin.ConnectDirect(_filterYUV.InputPin); _filterYUV.OutputPin.ConnectDirect(_filterH264Encoder.InputPin); _filterH264Encoder.OutputPin.ConnectDirect(_filterRTSPServer.InputPin); m_MediaControl = (IMediaControl)_graphBuilder; m_VideoWindow = (IVideoWindow)_graphBuilder; m_VideoWindow.put_Visible(0); }
public override void releaseCOM() { if (Initialized) { TextureBase[] _textures = null; _textures = this.textures; this.textures = null; var thread = new Thread(() => { Thread.Sleep(1000); if (_textures != null) { foreach (var texture in _textures) { if (texture != null) { texture.Dispose(); } } } }) { IsBackground = true }; thread.Start(); if (sampleGrabber != null) { Marshal.ReleaseComObject(sampleGrabber); sampleGrabber = null; } if (videoWindow != null) { Marshal.ReleaseComObject(videoWindow); videoWindow = null; } if (lavSplitter != null) { Marshal.ReleaseComObject(lavSplitter); lavSplitter = null; } if (lavVideoDecoder != null) { Marshal.ReleaseComObject(lavVideoDecoder); lavVideoDecoder = null; } if (lavAudioDecoder != null) { Marshal.ReleaseComObject(lavAudioDecoder); lavAudioDecoder = null; } if (soundDevice != null) { Marshal.ReleaseComObject(soundDevice); soundDevice = null; } if (videoRenderer != null) { Marshal.ReleaseComObject(videoRenderer); videoRenderer = null; } base.releaseCOM(); } }
public bool Build(RtpStream stream) { if (base.Build(PayloadType.dynamicVideo, stream)) { try { IVideoWindow ivw = (IVideoWindow)fgm; ivw.Caption = "Windows Media Gateway Preview"; int ws = ivw.WindowStyle; ws = ws & ~(0x00080000); // Remove WS_SYSMENU ivw.WindowStyle = ws; ivw.AutoShow = 0; if (visible) { ivw.Visible = VISIBLE; //0 is hidden, -1 is showing. } else { ivw.Visible = INVISIBLE; //0 is hidden, -1 is showing. } } catch (Exception e) { Debug.WriteLine("Failed to set video window properties: " + e.ToString()); eventLog.WriteEntry("Failed to set video window properties: " + e.ToString(), EventLogEntryType.Error, 1001); return(false); } return(true); } return(false); }
protected virtual void DoStopInternal(object state) { try { //ResetVolumeLevels(); #if HAVE_SAMPLES ReleaseAudioSampleGrabber(); #endif if (mediaControl != null) { mediaControl.Stop(); mediaControl = null; mediaPosition = null; videoWindow = null; basicVideo = null; basicAudio = null; mediaEvent = null; } GC.Collect(); } catch (Exception ex) { // This is running on other thread than the DSRenderer, // so its exceptions are not caught in MediaRenderer Logger.LogException(ex); } }
void DeInitDirectShow() { if (mediaControl != null) { mediaControl.StopWhenReady(); } if (mediaEventEx != null) { mediaEventEx.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); } if (videoWindow != null) { videoWindow.put_Visible(OABool.False); videoWindow.put_Owner(IntPtr.Zero); } Marshal.ReleaseComObject(mediaControl); mediaControl = null; Marshal.ReleaseComObject(mediaEventEx); mediaControl = null; Marshal.ReleaseComObject(videoWindow); videoWindow = null; Marshal.ReleaseComObject(graphBuilder); graphBuilder = null; Marshal.ReleaseComObject(captureGraphBuilder); captureGraphBuilder = null; Marshal.ReleaseComObject(outputRenderer); outputRenderer = null; Marshal.ReleaseComObject(aspectRatioControl); aspectRatioControl = null; Marshal.ReleaseComObject(aspectRatioControl9); aspectRatioControl9 = null; }
void InitDirectShow(IntPtr handle) { graphBuilder = (IGraphBuilder) new FilterGraph(); mediaControl = (IMediaControl)(IVideoWindow)graphBuilder; videoWindow = (IVideoWindow)(IMediaControl)graphBuilder; mediaEventEx = (IMediaEventEx)graphBuilder; captureGraphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); outputRenderer = (IBaseFilter) new VideoMixingRenderer9(); if (outputRenderer != null) { graphBuilder.AddFilter(outputRenderer, "Output"); aspectRatioControl = outputRenderer as IVMRAspectRatioControl; aspectRatioControl9 = outputRenderer as IVMRAspectRatioControl9; } var hr = mediaEventEx.SetNotifyWindow(handle, WM_GRAPHNOTIFY, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); hr = captureGraphBuilder.SetFiltergraph(graphBuilder); DsError.ThrowExceptionForHR(hr); graphBuilderRotEntry = new DsROTEntry(graphBuilder); }
// Starts playing a new cinematic public void PlayCinematic(string file, int x, int y, int w, int h) { // Lame bugfix: DirectShow and Fullscreen doesnt like eachother if (CVars.Instance.Get("r_fs", "0", CVarFlags.ARCHIVE).Integer == 1) { if (AlterGameState) { playing = true; StopCinematic(); } return; } // Check if file exists if (FileCache.Instance.Contains(file)) file = FileCache.Instance.GetFile(file).FullName; else { if (AlterGameState) { playing = true; StopCinematic(); } Common.Instance.WriteLine("PlayCinematic: Could not find video: {0}", file); return; } // Have the graph builder construct its the appropriate graph automatically this.graphBuilder = (IGraphBuilder)new FilterGraph(); int hr = graphBuilder.RenderFile(file, null); DsError.ThrowExceptionForHR(hr); mediaControl = (IMediaControl)this.graphBuilder; mediaEventEx = (IMediaEventEx)this.graphBuilder; videoWindow = this.graphBuilder as IVideoWindow; basicVideo = this.graphBuilder as IBasicVideo; // Setup the video window hr = this.videoWindow.put_Owner(Renderer.Instance.form.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); // Set the video size //int lWidth, lHeight; //hr = this.basicVideo.GetVideoSize(out lWidth, out lHeight); hr = this.videoWindow.SetWindowPosition(x, y, w, h); videoWindow.put_FullScreenMode((CVars.Instance.Get("r_fs", "0", CVarFlags.ARCHIVE).Integer == 1) ? OABool.True : OABool.False); DsError.ThrowExceptionForHR(hr); // Run the graph to play the media file hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); playing = true; if (AlterGameState) Client.Instance.state = CubeHags.common.ConnectState.CINEMATIC; Common.Instance.WriteLine("Playing cinematic: {0}", file); EventCode code; }
/// <summary> /// Open the file in <see cref="FilePath"/> and load it. /// </summary> private void OpenMediaFile() { ClosePlayer(); int hr = 0; this.graphBuilder = (IGraphBuilder) new FilterGraph(); hr = graphBuilder.RenderFile(this.FilePath, null); DsError.ThrowExceptionForHR(hr); this.mediaControl = (IMediaControl)this.graphBuilder; this.mediaEventEx = (IMediaEventEx)this.graphBuilder; this.mediaSeeking = (IMediaSeeking)this.graphBuilder; this.mediaPosition = (IMediaPosition)this.graphBuilder; this.videoWindow = this.graphBuilder as IVideoWindow; this.basicVideo = this.graphBuilder as IBasicVideo; int x, y; this.basicVideo.GetVideoSize(out x, out y); this.VideoSize = new Size(x, y); this.basicAudio = (IBasicAudio)this.graphBuilder; hr = this.mediaEventEx.SetNotifyWindow(notifyTarget, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_Owner(owner); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); videoWindow.SetWindowPosition(0, 0, Control.FromHandle(this.owner).Width, Control.FromHandle(this.owner).Height); double time; mediaPosition.get_Duration(out time); this.Length = (int)(time * 1000); this.State = PlayState.Opened; }
public HRESULT Dispose() { try { m_MediaControl.Stop(); m_VideoWindow.put_Visible(0); m_MediaControl = null; m_VideoWindow = null; if (_graphBuilder != null) { _graphBuilder.RemoveFilter(_filterCamera.Value); _graphBuilder.RemoveFilter(_filterVMR9Renderer.Value); _filterCamera.Dispose(); _filterVMR9Renderer.Dispose(); _filterVMR9Renderer = null; _filterCamera = null; Marshal.ReleaseComObject(_graphBuilder); _graphBuilder = null; } GC.Collect(); return(COMHelper.NOERROR); } catch { return(COMHelper.E_FAIL); } }
/// <summary> /// Build the graph to play the file /// </summary> private void BuildGraph() { // get the interfaces needed this._graphBuilder = (IGraphBuilder) new FilterGraph(); this._mediaControl = (IMediaControl)this._graphBuilder; this._mediaEvent = (IMediaEventEx)this._graphBuilder; this._mediaPosition = (IMediaPosition)this._graphBuilder; // use Intelligent Connect for the rest this._graphBuilder.RenderFile(this.FileName, null); // and the window this._vidWindow = (IVideoWindow)this._graphBuilder; this._vidWindow.put_Owner((IntPtr)this.Handle); this._vidWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); Rectangle rc = this.vidOwner.ClientRectangle; this._vidWindow.SetWindowPosition(0, 0, rc.Right, rc.Bottom); double duration = 0.0; this._mediaPosition.get_Duration(out duration); this.SetupProgressBar(duration); this.EnableButtons(this._enableControls); }
private void Stop() { if (null == m_fm) { return; } try { IMediaControl mc = m_fm as IMediaControl; mc.Stop(); //int lEventCode, lParam1, lParam2; //IMediaEventEx mee = m_fm as IMediaEventEx; //mee.SetNotifyWindow(0, 0, 0); //mee.GetEvent(out lEventCode, out lParam1, out lParam2, 0); //mee.FreeEventParams(lEventCode, lParam1, lParam2); IVideoWindow vw = m_fm as IVideoWindow; vw.Visible = 0; vw.Owner = 0; } catch (Exception) { } }
public void ResizeWindowToVideo() { IVideoWindow pVW = m_pRenderGraph as IVideoWindow; IBasicVideo pBV = m_pRenderGraph as IBasicVideo; if ((pVW != null) && (pBV != null)) { // size of new video int cx, cy; pBV.GetVideoSize(out cx, out cy); DsRect rcVideo = new DsRect(0, 0, cx, cy); // adjust from client size to window size WindowStyle style; pVW.get_WindowStyle(out style); //AdjustWindowRect(rcVideo, style, false); // get current window top/left int cxWindow, cyWindow; DsRect rc = new DsRect(); pVW.GetWindowPosition(out rc.left, out rc.top, out cxWindow, out cyWindow); // reposition video window with old top/left position and new size pVW.SetWindowPosition(rc.left, rc.top, rcVideo.right - rcVideo.left, rcVideo.bottom - rcVideo.top); } }
/// <summary> /// Creation of the fgm and the adding / removing of filters needs to happen on the /// same thread. So make sure it all happens on the UI thread. /// </summary> private void _RtpStream_FirstFrameReceived() { lock (fgmLock) { DisposeFgm(); Debug.Assert(fgm == null); // Create the DirectShow filter graph manager fgm = new FilgraphManagerClass(); IGraphBuilder iGB = (IGraphBuilder)fgm; rotID = FilterGraph.AddToRot((IGraphBuilder)fgm); IBaseFilter bfSource = RtpSourceClass.CreateInstance(); ((MSR.LST.MDShow.Filters.IRtpSource)bfSource).Initialize(rtpStream); iGB.AddFilter(bfSource, "RtpSource"); iGB.Render(Filter.GetPin(bfSource, _PinDirection.PINDIR_OUTPUT, Guid.Empty, Guid.Empty, false, 0)); DisableDXVA(fgm); // Render the video inside of the form iVW = (IVideoWindow)fgm; // Get the correct ratio to use for the video stretching // I would expect the fgm to always be castable to this, but I simply don't trust DShow IBasicVideo iBV = fgm as IBasicVideo; if (iBV != null) { int vidWidth, vidHeight; iBV.GetVideoSize(out vidWidth, out vidHeight); vidSrcRatio = (double)vidHeight / (double)vidWidth; } // Remove the border from the default DShow renderer UI int ws = WindowStyle; ws = ws & ~(0x00800000); // Remove WS_BORDER ws = ws & ~(0x00400000); // Remove WS_DLGFRAME WindowStyle = ws; iVW = null; uiState &= ~(int)FAudioVideo.UIState.RemoteVideoStopped; if (form != null) { ((FAudioVideo)form).UpdateVideoUI(uiState); } // FirstFrameReceived interprets fgmState as the *desired* state for the fgm // Because ResumePlayingVideo won't actually start if the state is already // Running, we change it to Stopped so that it will start if (IsPlaying && fgmState == FilterGraph.State.Running) { fgmState = FilterGraph.State.Stopped; ResumePlayingVideo(); } } }
private void Cleanup(bool stop) { if (this.fmc != null && stop) { this.fmc.Stop(); } if (this.ime != null) { this.ime.SetNotifyWindow(0, WM_GRAPHNOTIFY, 0); this.ime = null; } if (this.ivw != null) { this.ivw.Owner = 0; this.ivw = null; } if (this.isg != null) { Marshal.ReleaseComObject(this.isg); } if (this.fmc != null) { Marshal.ReleaseComObject(this.fmc); } if (this.iamsc != null) { Marshal.ReleaseComObject(this.iamsc); } if (this.icgb != null) { Marshal.ReleaseComObject(this.icgb); } }
private void ReleaseUnmangedResources() { try { if (_quartzVideo != null) { _quartzVideo.Owner = -1; } } catch { } if (_quartzFilgraphManager != null) { try { _quartzFilgraphManager.Stop(); Marshal.ReleaseComObject(_quartzFilgraphManager); _quartzFilgraphManager = null; } catch { } } _quartzVideo = null; }
public void Play(Resource resource) { // Have the graph builder construct its the appropriate graph automatically if (this.currentMediaFile.Equals(resource.FullName)) { return; } this.graphBuilder = (IGraphBuilder) new FilterGraph(); hr = this.graphBuilder.RenderFile(resource.FullName, null); DsError.ThrowExceptionForHR(hr); // 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 = this.graphBuilder as IVideoWindow; this.basicVideo = this.graphBuilder as IBasicVideo; // Query for audio interfaces, which may not be relevant for video-only files this.basicAudio = this.graphBuilder as IBasicAudio; this.MoveVideoWindow(); this.mediaControl.Run(); this.currentMediaFile = resource.FullName; }
protected override void WndProc(ref Message m) { switch (m.Msg) { case WMGraphNotify: { HandleGraphEvent(); break; } } // Pass this message to the video window for notification of system changes try { if (_videoWindow != null) { _videoWindow.NotifyOwnerMessage(m.HWnd, m.Msg, m.WParam, m.LParam); } } catch { _videoWindow = null; } base.WndProc(ref m); }
public void CloseInterfaces() { if (mediaControl != null) { int hr = mediaControl.StopWhenReady(); DsError.ThrowExceptionForHR(hr); } if (videoWindow != null) { videoWindow.put_Visible(OABool.False); videoWindow.put_Owner(IntPtr.Zero); } // Remove filter graph from the running object table. if (rot != null) { rot.Dispose(); rot = null; } // Release DirectShow interfaces. Marshal.ReleaseComObject(this.mediaControl); this.mediaControl = null; Marshal.ReleaseComObject(this.videoWindow); this.videoWindow = null; Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null; Marshal.ReleaseComObject(this.captureGraphBuilder); this.captureGraphBuilder = null; }
protected void derenderGraph() { if (this.mediaControl != null) { this.mediaControl.Stop(); } if (this.videoWindow != null) { this.videoWindow.put_Visible(0); this.videoWindow.put_Owner(IntPtr.Zero); this.videoWindow = null; } if (this.PreviewWindow != null) { this.previewWindow.Resize -= new EventHandler(this.onPreviewWindowResize); } if (this.graphState >= GraphState.Rendered) { this.graphState = GraphState.Created; this.isCaptureRendered = false; this.isPreviewRendered = false; if (this.videoDeviceFilter != null) { this.removeDownstream(this.videoDeviceFilter, this.videoCompressor == null); } if (this.audioDeviceFilter != null) { this.removeDownstream(this.audioDeviceFilter, this.audioCompressor == null); } this.muxFilter = null; this.fileWriterFilter = null; this.baseGrabFlt = null; } }
private void ShowVideoWindow(Control hControl) { int hr; // get the video window from the graph IVideoWindow videoWindow = (DirectShowLib.IVideoWindow)m_graphBuilder; //IBasicVideo basicFilter = (IBasicVideo) m_graphBuilder; //basicFilter.put_DestinationWidth(320); //basicFilter.put_DestinationHeight(240); // Set the owener of the videoWindow to an IntPtr of some sort (the Handle of any control - could be a form / button etc.) hr = videoWindow.put_Owner(hControl.Handle); DsError.ThrowExceptionForHR(hr); // Set the style of the video window hr = videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); // Position video window in client rect of main application window hr = videoWindow.SetWindowPosition(0, 0, hControl.Width, hControl.Height); DsError.ThrowExceptionForHR(hr); // Make the video window visible hr = videoWindow.put_Visible(OABool.True); DsError.ThrowExceptionForHR(hr); Start(); }
private void killOutput() { IVideoWindow videoWindow = this.getVideoWindow(); videoWindow.put_Visible(OABool.False); videoWindow.put_Owner(IntPtr.Zero); }
//Метод CleanUp (Зачистка графов) public void CleanUp() { if (mediaControl != null) mediaControl.Stop(); CurrentStatus = mStatus.Stop; if (videoWindow != null) { videoWindow.put_Visible(0); videoWindow.put_Owner(new IntPtr(0)); } if (mediaControl != null) mediaControl = null; if (mediaPosition != null) mediaPosition = null; if (mediaEventEx != null) mediaEventEx = null; if (mediaEvent != null) mediaEvent = null; if (videoWindow != null) videoWindow = null; if (basicAudio != null) basicAudio = null; if (graphBuilder != null) graphBuilder = null; }
/// <summary> /// Plays the given mediafile in the internal mediaplayer /// </summary> /// <param name="FilePath">File to play</param> public void ShowMedia(string FilePath) { StopMedia(); Lbl_CurrentMedia.Text = Path.GetFileName(FilePath); m_objFilterGraph = new FilgraphManager(); m_objFilterGraph.RenderFile(FilePath); m_objBasicAudio = m_objFilterGraph as IBasicAudio; try { m_objVideoWindow = m_objFilterGraph as IVideoWindow; m_objVideoWindow.Owner = (int)panel2.Handle; //m_objVideoWindow.Owner = (int)panel1.Handle; m_objVideoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN; m_objVideoWindow.SetWindowPosition(panel2.ClientRectangle.Left, panel2.ClientRectangle.Top, panel2.ClientRectangle.Width, panel2.ClientRectangle.Height); } catch (Exception ex) { Console.WriteLine(ex); m_objVideoWindow = null; } m_objMediaEvent = m_objFilterGraph as IMediaEvent; m_objMediaEventEx = m_objFilterGraph as IMediaEventEx; m_objMediaEventEx.SetNotifyWindow((int)this.Handle, WM_GRAPHNOTIFY, 0); m_objMediaPosition = m_objFilterGraph as IMediaPosition; m_objMediaControl = m_objFilterGraph as IMediaControl; m_objMediaControl.Run(); m_CurrentStatus = MediaStatus.Running; UpdateMediaButtons(); //UpdateStatusBar(); //UpdateToolBar(); }
private void cmdOpen_Click(object sender, EventArgs e) { // Allow the user to choose a file. OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*"; if (DialogResult.OK == openFileDialog.ShowDialog()) { // Stop the playback for the current movie, if it exists. if (mc != null) mc.Stop(); mc = null; videoWindow = null; // Load the movie file. FilgraphManager graphManager = new FilgraphManager(); graphManager.RenderFile(openFileDialog.FileName); // Attach the view to a picture box on the form. try { videoWindow = (IVideoWindow)graphManager; videoWindow.Owner = (int)pictureBox1.Handle; videoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN; videoWindow.SetWindowPosition(pictureBox1.ClientRectangle.Left, pictureBox1.ClientRectangle.Top, pictureBox1.ClientRectangle.Width, pictureBox1.ClientRectangle.Height); } catch { // An error can occur if the file does not have a vide // source (for example, an MP3 file.) // You can ignore this error and still allow playback to // continue (without any visualization). } // Start the playback (asynchronously). mc = (IMediaControl)graphManager; mc.Run(); } }
/** * To clean up the FilterGraph and other Objects * */ public void CleanUp() { if (m_objMediaControl != null) m_objMediaControl.Stop(); if (m_objMediaEventEx != null) m_objMediaEventEx.SetNotifyWindow(0, 0, 0); if (m_objVideoWindow != null) { m_objVideoWindow.Visible = 0; m_objVideoWindow.Owner = 0; } if (m_objMediaControl != null) m_objMediaControl = null; if (m_objMediaPosition != null) m_objMediaPosition = null; if (m_objMediaEventEx != null) m_objMediaEventEx = null; if (m_objMediaEvent != null) m_objMediaEvent = null; if (m_objVideoWindow != null) m_objVideoWindow = null; if (m_objBasicAudio != null) m_objBasicAudio = null; if (m_objFilterGraph != null) m_objFilterGraph = null; }
/// <summary> create the used COM components and get the interfaces. </summary> protected virtual bool GetDVDInterfaces(string path) { int hr; //Type comtype = null; object comobj = null; _freeNavigator = true; _dvdInfo = null; _dvdCtrl = null; bool useAC3Filter = false; string dvdNavigator = ""; string aspectRatioMode = ""; string displayMode = ""; _videoPref = DvdPreferredDisplayMode.DisplayContentDefault; using (MediaPortal.Profile.Settings xmlreader = new MPSettings()) { dvdNavigator = xmlreader.GetValueAsString("dvdplayer", "navigator", "DVD Navigator"); aspectRatioMode = xmlreader.GetValueAsString("dvdplayer", "armode", "").ToLower(); dvdNavigator = "dslibdvdnav"; if (aspectRatioMode == "crop") { arMode = AspectRatioMode.Crop; } if (aspectRatioMode == "letterbox") { arMode = AspectRatioMode.LetterBox; } if (aspectRatioMode == "stretch") { arMode = AspectRatioMode.Stretched; } //if ( aspectRatioMode == "stretch" ) arMode = AspectRatioMode.zoom14to9; if (aspectRatioMode == "follow stream") { arMode = AspectRatioMode.StretchedAsPrimary; } useAC3Filter = xmlreader.GetValueAsBool("dvdplayer", "ac3", false); displayMode = xmlreader.GetValueAsString("dvdplayer", "displaymode", "").ToLower(); if (displayMode == "default") { _videoPref = DvdPreferredDisplayMode.DisplayContentDefault; } if (displayMode == "16:9") { _videoPref = DvdPreferredDisplayMode.Display16x9; } if (displayMode == "4:3 pan scan") { _videoPref = DvdPreferredDisplayMode.Display4x3PanScanPreferred; } if (displayMode == "4:3 letterbox") { _videoPref = DvdPreferredDisplayMode.Display4x3LetterBoxPreferred; } } try { _dvdGraph = (IDvdGraphBuilder)new DvdGraphBuilder(); hr = _dvdGraph.GetFiltergraph(out _graphBuilder); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } _rotEntry = new DsROTEntry((IFilterGraph)_graphBuilder); _vmr9Filter = (IBaseFilter)new VideoMixingRenderer9(); IVMRFilterConfig9 config = _vmr9Filter as IVMRFilterConfig9; hr = config.SetNumberOfStreams(1); hr = config.SetRenderingMode(VMR9Mode.Windowless); windowlessCtrl = (IVMRWindowlessControl9)_vmr9Filter; windowlessCtrl.SetVideoClippingWindow(this.panVideoWin.Handle); // config.SetRenderingPrefs(VMR9RenderPrefs. _graphBuilder.AddFilter(_vmr9Filter, "Video Mixing Renderer 9"); // _vmr7 = new VMR7Util(); // _vmr7.AddVMR7(_graphBuilder); try { _dvdbasefilter = DirectShowUtil.AddFilterToGraph(_graphBuilder, dvdNavigator); if (_dvdbasefilter != null) { IDvdControl2 cntl = (IDvdControl2)_dvdbasefilter; if (cntl != null) { _dvdInfo = (IDvdInfo2)cntl; _dvdCtrl = (IDvdControl2)cntl; if (path != null) { if (path.Length != 0) { cntl.SetDVDDirectory(path); } } _dvdCtrl.SetOption(DvdOptionFlag.HMSFTimeCodeEvents, true); // use new HMSF timecode format _dvdCtrl.SetOption(DvdOptionFlag.ResetOnStop, false); AddPreferedCodecs(_graphBuilder); DirectShowUtil.RenderOutputPins(_graphBuilder, _dvdbasefilter); // _videoWin = _graphBuilder as IVideoWindow; _freeNavigator = false; } //DirectShowUtil.ReleaseComObject( _dvdbasefilter); _dvdbasefilter = null; } } catch (Exception ex) { string strEx = ex.Message; } Guid riid; if (_dvdInfo == null) { riid = typeof(IDvdInfo2).GUID; hr = _dvdGraph.GetDvdInterface(riid, out comobj); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } _dvdInfo = (IDvdInfo2)comobj; comobj = null; } if (_dvdCtrl == null) { riid = typeof(IDvdControl2).GUID; hr = _dvdGraph.GetDvdInterface(riid, out comobj); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } _dvdCtrl = (IDvdControl2)comobj; comobj = null; } _mediaCtrl = (IMediaControl)_graphBuilder; _mediaEvt = (IMediaEventEx)_graphBuilder; _basicAudio = _graphBuilder as IBasicAudio; _mediaPos = (IMediaPosition)_graphBuilder; _mediaSeek = (IMediaSeeking)_graphBuilder; _mediaStep = (IVideoFrameStep)_graphBuilder; _basicVideo = _graphBuilder as IBasicVideo2; _videoWin = _graphBuilder as IVideoWindow; // disable Closed Captions! IBaseFilter baseFilter; _graphBuilder.FindFilterByName("Line 21 Decoder", out baseFilter); if (baseFilter == null) { _graphBuilder.FindFilterByName("Line21 Decoder", out baseFilter); } if (baseFilter != null) { _line21Decoder = (IAMLine21Decoder)baseFilter; if (_line21Decoder != null) { AMLine21CCState state = AMLine21CCState.Off; hr = _line21Decoder.SetServiceState(state); if (hr == 0) { logger.Info("DVDPlayer:Closed Captions disabled"); } else { logger.Info("DVDPlayer:failed 2 disable Closed Captions"); } } } /* // get video window if (_videoWin==null) { riid = typeof( IVideoWindow ).GUID; hr = _dvdGraph.GetDvdInterface( ref riid, out comobj ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); _videoWin = (IVideoWindow) comobj; comobj = null; } */ // GetFrameStepInterface(); DirectShowUtil.SetARMode(_graphBuilder, arMode); DirectShowUtil.EnableDeInterlace(_graphBuilder); //m_ovMgr = new OVTOOLLib.OvMgrClass(); //m_ovMgr.SetGraph(_graphBuilder); return true; } catch (Exception) { //MessageBox.Show( this, "Could not get interfaces\r\n" + ee.Message, "DVDPlayer.NET", MessageBoxButtons.OK, MessageBoxIcon.Stop ); CloseDVDInterfaces(); return false; } finally { if (comobj != null) { DirectShowUtil.ReleaseComObject(comobj); } comobj = null; } }
/// <summary> do cleanup and release DirectShow. </summary> protected virtual void CloseDVDInterfaces() { if (_graphBuilder == null) { return; } int hr; try { logger.Info("DVDPlayer:cleanup DShow graph"); if (_mediaCtrl != null) { hr = _mediaCtrl.Stop(); _mediaCtrl = null; } _state = PlayState.Stopped; _mediaEvt = null; _visible = false; _videoWin = null; // videoStep = null; _dvdCtrl = null; _dvdInfo = null; _basicVideo = null; _basicAudio = null; _mediaPos = null; _mediaSeek = null; _mediaStep = null; //if (_vmr7 != null) //{ // _vmr7.RemoveVMR7(); //} //_vmr7 = null; if (_vmr9Filter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_vmr9Filter)) > 0) { ; } _vmr9Filter = null; } if (_dvdbasefilter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_dvdbasefilter)) > 0) { ; } _dvdbasefilter = null; } if (_cmdOption != null) { DirectShowUtil.ReleaseComObject(_cmdOption); } _cmdOption = null; _pendingCmd = false; if (_line21Decoder != null) { while ((hr = DirectShowUtil.ReleaseComObject(_line21Decoder)) > 0) { ; } _line21Decoder = null; } if (_graphBuilder != null) { DirectShowUtil.RemoveFilters(_graphBuilder); if (_rotEntry != null) { _rotEntry.Dispose(); _rotEntry = null; } while ((hr = DirectShowUtil.ReleaseComObject(_graphBuilder)) > 0) { ; } _graphBuilder = null; } if (_dvdGraph != null) { while ((hr = DirectShowUtil.ReleaseComObject(_dvdGraph)) > 0) { ; } _dvdGraph = null; } _state = PlayState.Init; } catch (Exception ex) { logger.Error("DVDPlayer:exception while cleanuping DShow graph {0} {1}", ex.Message, ex.StackTrace); } }
/// <summary> /// Disconnect and remove all filters except the device /// and compressor filters. This is the opposite of /// renderGraph(). Soem properties such as FrameRate /// can only be set when the device output pins are not /// connected. /// </summary> protected void derenderGraph() { // Stop the graph if it is running (ignore errors) if ( mediaControl != null ) mediaControl.Stop(); // Free the preview window (ignore errors) if ( videoWindow != null ) { #if DSHOWNET videoWindow.put_Visible(DsHlp.OAFALSE); #else videoWindow.put_Visible(OABool.False); #endif videoWindow.put_Owner( IntPtr.Zero ); videoWindow = null; } // Remove the Resize event handler if ( PreviewWindow != null ) previewWindow.Resize -= new EventHandler( onPreviewWindowResize ); if ( (int)graphState >= (int)GraphState.Rendered ) { // Update the state graphState = GraphState.Created; isCaptureRendered = false; isPreviewRendered = false; // Disconnect all filters downstream of the // video and audio devices. If we have a compressor // then disconnect it, but don't remove it if (videoDeviceFilter != null) { try { removeDownstream(videoDeviceFilter, (videoCompressor == null)); } catch { Debug.WriteLine("Error removeDownstream videoDeviceFilter"); } } if (audioDeviceFilter != null) { try { removeDownstream(audioDeviceFilter, (audioCompressor == null)); } catch { Debug.WriteLine("Error removeDownstream audioDeviceFilter"); } } // These filters should have been removed by the // calls above. (Is there anyway to check?) muxFilter = null; fileWriterFilter = null; this.videoRendererFilter = null; this.deInterlaceFilter = null; } }
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 (this.mediaEventEx != null) { hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); } #if DEBUG if (rot != null) { rot.Dispose(); rot = null; } #endif // 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; GC.Collect(); } } catch { } }
private void ReleaseUnmangedResources() { try { if (_quartzVideo != null) _quartzVideo.Owner = -1; } catch { } if (_quartzFilgraphManager != null) { try { _quartzFilgraphManager.Stop(); Marshal.ReleaseComObject(_quartzFilgraphManager); _quartzFilgraphManager = null; } catch { } } _quartzVideo = null; }
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 override void Initialize(Control ownerControl, string videoFileName, EventHandler onVideoLoaded, EventHandler onVideoEnded) { const int wsChild = 0x40000000; var extension = System.IO.Path.GetExtension(videoFileName); if (extension == null) { return; } string ext = extension.ToLower(); bool isAudio = ext == ".mp3" || ext == ".wav" || ext == ".wma" || ext == ".m4a"; OnVideoLoaded = onVideoLoaded; OnVideoEnded = onVideoEnded; VideoFileName = videoFileName; owner = ownerControl; quartzFilgraphManager = new FilgraphManager(); quartzFilgraphManager.RenderFile(VideoFileName); if (!isAudio) { quartzVideo = quartzFilgraphManager as IVideoWindow; if (quartzVideo != null) { quartzVideo.Owner = (int)ownerControl.Handle; quartzVideo.SetWindowPosition(0, 0, ownerControl.Width, ownerControl.Height); quartzVideo.WindowStyle = wsChild; } } //Play(); if (!isAudio) { var basicVideo = quartzFilgraphManager as IBasicVideo; if (basicVideo != null) { basicVideo.GetVideoSize(out sourceWidth, out sourceHeight); } } owner.Resize += OwnerControlResize; mediaPosition = (IMediaPosition)quartzFilgraphManager; if (OnVideoLoaded != null) { videoLoader = new BackgroundWorker(); videoLoader.RunWorkerCompleted += VideoLoaderRunWorkerCompleted; videoLoader.DoWork += VideoLoaderDoWork; videoLoader.RunWorkerAsync(); } OwnerControlResize(this, null); videoEndTimer = new Timer { Interval = 500 }; videoEndTimer.Tick += VideoEndTimerTick; videoEndTimer.Start(); if (isAudio) { return; } if (quartzVideo != null) { quartzVideo.MessageDrain = (int)ownerControl.Handle; } }
/// <summary> /// Builds the DVD DirectShow graph /// </summary> private void BuildGraph() { try { FreeResources(); int hr; /* Create our new graph */ m_graph = (IGraphBuilder)new FilterGraphNoThread(); #if DEBUG m_rot = new DsROTEntry(m_graph); #endif /* We are going to use the VMR9 for now. The EVR does not * seem to work with the interactive menus yet. It should * play Dvds fine otherwise */ var rendererType = VideoRendererType.VideoMixingRenderer9; /* Creates and initializes a new renderer ready to render to WPF */ m_renderer = CreateVideoRenderer(rendererType, m_graph, 2); /* Do some VMR9 specific stuff */ if (rendererType == VideoRendererType.VideoMixingRenderer9) { var mixer = m_renderer as IVMRMixerControl9; if(mixer != null) { VMR9MixerPrefs dwPrefs; mixer.GetMixingPrefs(out dwPrefs); dwPrefs &= ~VMR9MixerPrefs.RenderTargetMask; dwPrefs |= VMR9MixerPrefs.RenderTargetYUV; /* Enable this line to prefer YUV */ //hr = mixer.SetMixingPrefs(dwPrefs); } } /* Create a new DVD Navigator. */ var dvdNav = (IBaseFilter)new DVDNavigator(); /* The DVDControl2 interface lets us control DVD features */ m_dvdControl = dvdNav as IDvdControl2; if (m_dvdControl == null) throw new Exception("Could not QueryInterface the IDvdControl2 interface"); /* QueryInterface the DVDInfo2 */ m_dvdInfo = dvdNav as IDvdInfo2; /* If a Dvd directory has been set then use it, if not, let DShow find the Dvd */ if (!string.IsNullOrEmpty(DvdDirectory)) { hr = m_dvdControl.SetDVDDirectory(DvdDirectory); DsError.ThrowExceptionForHR(hr); } /* This gives us the DVD time in Hours-Minutes-Seconds-Frame time format, and other options */ hr = m_dvdControl.SetOption(DvdOptionFlag.HMSFTimeCodeEvents, true); DsError.ThrowExceptionForHR(hr); /* If the graph stops, resume at the same point */ m_dvdControl.SetOption(DvdOptionFlag.ResetOnStop, false); hr = m_graph.AddFilter(dvdNav, "DVD Navigator"); DsError.ThrowExceptionForHR(hr); IPin dvdVideoPin = null; IPin dvdAudioPin = null; IPin dvdSubPicturePin = null; IPin dvdNavPin; int i = 0; /* Loop all the output pins on the DVD Navigator, trying to find which pins are which. * We could more easily find the pins by name, but this is more fun...and more flexible * if we ever want to use a 3rd party DVD navigator that used different pin names */ while ((dvdNavPin = DsFindPin.ByDirection(dvdNav, PinDirection.Output, i)) != null) { var mediaTypes = new AMMediaType[1]; IntPtr pFetched = IntPtr.Zero; IEnumMediaTypes mediaTypeEnum; dvdNavPin.EnumMediaTypes(out mediaTypeEnum); /* Loop over each of the mediaTypes of each pin */ while (mediaTypeEnum.Next(1, mediaTypes, pFetched) == 0) { AMMediaType mediaType = mediaTypes[0]; /* This will be the video stream pin */ if (mediaType.subType == MediaSubType.Mpeg2Video) { /* Keep the ref and we'll work with it later */ dvdVideoPin = dvdNavPin; break; } /* This will be the audio stream pin */ if (mediaType.subType == MediaSubType.DolbyAC3 || mediaType.subType == MediaSubType.Mpeg2Audio) { /* Keep the ref and we'll work with it later */ dvdAudioPin = dvdNavPin; break; } /* This is the Dvd sub picture pin. This generally * shows overlays for Dvd menus and sometimes closed captions */ if (mediaType.subType == DVD_SUBPICTURE_TYPE) { /* Keep the ref and we'll work with it later */ dvdSubPicturePin = dvdNavPin; break; } } mediaTypeEnum.Reset(); Marshal.ReleaseComObject(mediaTypeEnum); i++; } /* This is the windowed renderer. This is *NEEDED* in order * for interactive menus to work with the other VMR9 in renderless mode */ var dummyRenderer = (IBaseFilter)new VideoMixingRenderer9(); var dummyRendererConfig = (IVMRFilterConfig9)dummyRenderer; /* In order for this interactive menu trick to work, the VMR9 * must be set to Windowed. We will make sure the window is hidden later on */ hr = dummyRendererConfig.SetRenderingMode(VMR9Mode.Windowed); DsError.ThrowExceptionForHR(hr); hr = dummyRendererConfig.SetNumberOfStreams(1); DsError.ThrowExceptionForHR(hr); hr = m_graph.AddFilter(dummyRenderer, "Dummy Windowed"); DsError.ThrowExceptionForHR(hr); if (dvdAudioPin != null) { /* This should render out to the default audio device. We * could modify this code here to go out any audio * device, such as SPDIF or another sound card */ hr = m_graph.Render(dvdAudioPin); DsError.ThrowExceptionForHR(hr); } /* Get the first input pin on our dummy renderer */ m_dummyRendererPin = DsFindPin.ByConnectionStatus(dummyRenderer, /* Filter to search */ PinConnectedStatus.Unconnected, 0); /* Get an available pin on our real renderer */ IPin rendererPin = DsFindPin.ByConnectionStatus(m_renderer, /* Filter to search */ PinConnectedStatus.Unconnected, 0); /* Pin index */ /* Connect the pin to the renderer */ hr = m_graph.Connect(dvdVideoPin, rendererPin); DsError.ThrowExceptionForHR(hr); /* Get the next available pin on our real renderer */ rendererPin = DsFindPin.ByConnectionStatus(m_renderer, /* Filter to search */ PinConnectedStatus.Unconnected, 0); /* Pin index */ /* Render the sub picture, which will connect * the DVD navigator to the codec, not the renderer */ hr = m_graph.Render(dvdSubPicturePin); DsError.ThrowExceptionForHR(hr); /* These are the subtypes most likely to be our dvd subpicture */ var preferedSubpictureTypes = new[]{MediaSubType.ARGB4444, MediaSubType.AI44, MediaSubType.AYUV, MediaSubType.ARGB32}; IPin dvdSubPicturePinOut = null; /* Find what should be the subpicture pin out */ foreach (var guidType in preferedSubpictureTypes) { dvdSubPicturePinOut = FindPinInGraphByMediaType(guidType, /* GUID of the media type being searched for */ PinDirection.Output, m_graph); /* Our current graph */ if (dvdSubPicturePinOut != null) break; } if (dvdSubPicturePinOut == null) throw new Exception("Could not find the sub picture pin out"); /* Here we connec thte Dvd sub picture pin to the video renderer. * This enables the overlays on Dvd menus and some closed * captions to be rendered. */ hr = m_graph.Connect(dvdSubPicturePinOut, rendererPin); DsError.ThrowExceptionForHR(hr); /* Search for the Line21 out in the graph */ IPin line21Out = FindPinInGraphByMediaType(MediaType.AuxLine21Data, PinDirection.Output, m_graph); if (line21Out == null) throw new Exception("Could not find the Line21 pin out"); /* We connect our line21Out out in to the dummy renderer * this is what ultimatly makes interactive DVDs work with * VMR9 in renderless (for WPF) */ hr = m_graph.Connect(line21Out, m_dummyRendererPin); DsError.ThrowExceptionForHR(hr); /* This is the dummy renderers Win32 window. */ m_dummyRenderWindow = dummyRenderer as IVideoWindow; if (m_dummyRenderWindow == null) throw new Exception("Could not QueryInterface for IVideoWindow"); ConfigureDummyWindow(); /* Setup our base classes with this filter graph */ SetupFilterGraph(m_graph); /* Sets the NaturalVideoWidth/Height */ SetNativePixelSizes(m_renderer); } catch (Exception ex) { FreeResources(); InvokeMediaFailed(new MediaFailedEventArgs(ex.Message, ex)); return; } InvokeMediaOpened(); }
/// <summary> /// Frees any allocated or unmanaged resources /// </summary> protected override void FreeResources() { base.FreeResources(); #if DEBUG if (m_rot != null) m_rot.Dispose(); #endif if (m_dummyRendererPin != null) { Marshal.ReleaseComObject(m_dummyRendererPin); m_dummyRendererPin = null; } if (m_dummyRenderWindow != null) { Marshal.ReleaseComObject(m_dummyRenderWindow); m_dummyRenderWindow = null; } if (m_renderer != null) { Marshal.ReleaseComObject(m_renderer); m_renderer = null; } if (m_dvdInfo != null) { Marshal.ReleaseComObject(m_dvdInfo); m_dvdInfo = null; } if (m_dvdControl != null) { Marshal.ReleaseComObject(m_dvdControl); m_dvdControl = null; } if (m_graph != null) { Marshal.ReleaseComObject(m_graph); m_graph = null; } }
private void InitVideoWindow() { if (Render == null) return; videoWindow = (IVideoWindow)graphBuilder; //Set the owener of the videoWindow to an IntPtr of some sort (the Handle of any control - could be a form / button etc.) var hr = videoWindow.put_Owner(Render.Handle); DsError.ThrowExceptionForHR(hr); //Set the style of the video window hr = videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings); DsError.ThrowExceptionForHR(hr); // Position video window in client rect of main application window //hr = videoWindow.SetWindowPosition(0, 0, Render.Width, Render.Height); Resize(); DsError.ThrowExceptionForHR(hr); videoWindow.put_Visible(OABool.True); Render.SizeChanged -= new EventHandler(onResize); Render.SizeChanged += new EventHandler(onResize); }
private void DisableVideoWindow() { // Free the preview window (ignore errors) if (videoWindow != null) { videoWindow.put_Visible(OABool.False); videoWindow.put_Owner(IntPtr.Zero); videoWindow = null; } // Remove the Resize event handler if (Render != null) Render.Resize -= new EventHandler(onResize); }
/// <summary> /// Completely tear down a filter graph and /// release all associated resources. /// </summary> protected void destroyGraph() { // Derender the graph (This will stop the graph // and release preview window. It also destroys // half of the graph which is unnecessary but // harmless here.) (ignore errors) try{ derenderGraph(); } catch {} // Update the state after derender because it // depends on correct status. But we also want to // update the state as early as possible in case // of error. graphState = GraphState.Null; isCaptureRendered = false; isPreviewRendered = false; // Remove graph from the ROT #if DSHOWNET if ( rotCookie != 0 ) { DsROT.RemoveGraphFromRot( ref rotCookie ); rotCookie = 0; } #else if (rotCookie != null) { rotCookie.Dispose(); rotCookie = null; } #endif // Remove filters from the graph // This should be unnecessary but the Nvidia WDM // video driver cannot be used by this application // again unless we remove it. Ideally, we should // simply enumerate all the filters in the graph // and remove them. (ignore errors) if ( muxFilter != null ) graphBuilder.RemoveFilter( muxFilter ); if ( videoCompressorFilter != null ) graphBuilder.RemoveFilter( videoCompressorFilter ); if ( audioCompressorFilter != null ) graphBuilder.RemoveFilter( audioCompressorFilter ); if ( videoDeviceFilter != null ) graphBuilder.RemoveFilter( videoDeviceFilter ); if ( audioDeviceFilter != null ) graphBuilder.RemoveFilter( audioDeviceFilter ); if(this.videoRendererFilter != null) { this.graphBuilder.RemoveFilter(this.videoRendererFilter); } // Clean up properties if ( videoSources != null ) videoSources.Dispose(); videoSources = null; if ( audioSources != null ) audioSources.Dispose(); audioSources = null; this.PropertyPages = null; // Disposal done within PropertyPages if ( tuner != null ) tuner.Dispose(); tuner = null; // #if NEWCODE if(this.tvAudio != null) { Marshal.ReleaseComObject(this.tvAudio); tvAudio = null; } if(this.dxUtils != null) { this.dxUtils.Dispose(); this.dxUtils = null; } // #endif // Cleanup if ( graphBuilder != null ) Marshal.ReleaseComObject( graphBuilder ); graphBuilder = null; if ( captureGraphBuilder != null ) Marshal.ReleaseComObject( captureGraphBuilder ); captureGraphBuilder = null; if ( muxFilter != null ) Marshal.ReleaseComObject( muxFilter ); muxFilter = null; if ( fileWriterFilter != null ) Marshal.ReleaseComObject( fileWriterFilter ); fileWriterFilter = null; if ( videoDeviceFilter != null ) Marshal.ReleaseComObject( videoDeviceFilter ); videoDeviceFilter = null; if ( audioDeviceFilter != null ) Marshal.ReleaseComObject( audioDeviceFilter ); audioDeviceFilter = null; if ( videoCompressorFilter != null ) Marshal.ReleaseComObject( videoCompressorFilter ); videoCompressorFilter = null; if ( audioCompressorFilter != null ) Marshal.ReleaseComObject( audioCompressorFilter ); audioCompressorFilter = null; // #if NEWCODE this.DisposeSampleGrabber(); // #endif if(this.videoRendererFilter != null) { Marshal.ReleaseComObject(this.videoRendererFilter); this.videoRendererFilter = null; } // These are copies of graphBuilder mediaControl = null; videoWindow = null; // For unmanaged objects we haven't released explicitly GC.Collect(); }
private void Cleanup() { if (graphBuilder == null) { return; } int hr; Log.Info("RTSPPlayer:cleanup DShow graph"); try { if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.Vmr9MediaCtrl(_mediaCtrl); VMR9Util.g_vmr9.Enable(false); } if (mediaEvt != null) { hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); } videoWin = graphBuilder as IVideoWindow; if (videoWin != null && GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR) { videoWin.put_Owner(IntPtr.Zero); videoWin.put_Visible(OABool.False); } _mediaCtrl = null; mediaEvt = null; _mediaSeeking = null; mediaPos = null; basicAudio = null; basicVideo = null; videoWin = null; SubEngine.GetInstance().FreeSubtitles(); if (graphBuilder != null) { DirectShowUtil.RemoveFilters(graphBuilder); if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } DirectShowUtil.FinalReleaseComObject(graphBuilder); graphBuilder = null; } if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.SafeDispose(); VMR9Util.g_vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; if (_mpegDemux != null) { Log.Info("cleanup mpegdemux"); DirectShowUtil.FinalReleaseComObject(_mpegDemux); _mpegDemux = null; } if (_rtspSource != null) { Log.Info("cleanup _rtspSource"); DirectShowUtil.FinalReleaseComObject(_rtspSource); _rtspSource = null; } if (_subtitleFilter != null) { DirectShowUtil.FinalReleaseComObject(_subtitleFilter); _subtitleFilter = null; if (this.dvbSubRenderer != null) { this.dvbSubRenderer.SetPlayer(null); } this.dvbSubRenderer = null; } if (vobSub != null) { Log.Info("cleanup vobSub"); DirectShowUtil.FinalReleaseComObject(vobSub); vobSub = null; } } catch (Exception ex) { Log.Error("RTSPPlayer: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace); } //switch back to directx windowed mode Log.Info("RTSPPlayer: Disabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null); GUIWindowManager.SendMessage(msg); }
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 Cleanup(bool stop) { if (this.fmc != null && stop) { this.fmc.Stop(); } if (this.ime != null) { this.ime.SetNotifyWindow(0, WM_GRAPHNOTIFY, 0); this.ime = null; } if (this.ivw != null) { this.ivw.Owner = 0; this.ivw = null; } if (this.isg != null) Marshal.ReleaseComObject(this.isg); if (this.fmc != null) Marshal.ReleaseComObject(this.fmc); if (this.iamsc != null) Marshal.ReleaseComObject(this.iamsc); if (this.icgb != null) Marshal.ReleaseComObject(this.icgb); }
/// <summary> do cleanup and release DirectShow. </summary> protected void CloseInterfaces() { if (_graphBuilder == null) { return; } int hr; Log.Debug("BDPlayer: Cleanup DShow graph {0}", GUIGraphicsContext.InVmr9Render); try { BDOSDRenderer.Release(); if (_mediaCtrl != null) { int counter = 0; FilterState state; hr = _mediaCtrl.Stop(); hr = _mediaCtrl.GetState(10, out state); while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render) { Thread.Sleep(100); hr = _mediaCtrl.GetState(10, out state); counter++; if (counter >= 30) { if (state != FilterState.Stopped) Log.Error("BDPlayer: graph still running"); if (GUIGraphicsContext.InVmr9Render) Log.Error("BDPlayer: in renderer"); break; } } _mediaCtrl = null; } if (_vmr9 != null) { _vmr9.Enable(false); } if (_mediaEvt != null) { hr = _mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); _mediaEvt = null; } _videoWin = _graphBuilder as IVideoWindow; if (_videoWin != null) { hr = _videoWin.put_Visible(OABool.False); hr = _videoWin.put_Owner(IntPtr.Zero); _videoWin = null; } _mediaSeeking = null; _basicAudio = null; _basicVideo = null; _ireader = null; #region Cleanup Sebastiii if (VideoCodec != null) { DirectShowUtil.ReleaseComObject(VideoCodec, 5000); VideoCodec = null; Log.Info("BDPlayer: Cleanup VideoCodec"); } if (AudioCodec != null) { DirectShowUtil.ReleaseComObject(AudioCodec, 5000); AudioCodec = null; Log.Info("BDPlayer: Cleanup AudioCodec"); } if (_audioRendererFilter != null) { while (DirectShowUtil.ReleaseComObject(_audioRendererFilter) > 0) ; _audioRendererFilter = null; Log.Info("BDPlayer: Cleanup AudioRenderer"); } //Test to ReleaseComObject from PostProcessFilter list objects. if (PostProcessFilterVideo.Count > 0) { foreach (var ppFilter in PostProcessFilterVideo) { if (ppFilter.Value != null) DirectShowUtil.ReleaseComObject(ppFilter.Value, 5000); } PostProcessFilterVideo.Clear(); Log.Info("BDPlayer: Cleanup PostProcessVideo"); } //Test to ReleaseComObject from PostProcessFilter list objects. if (PostProcessFilterAudio.Count > 0) { foreach (var ppFilter in PostProcessFilterAudio) { if (ppFilter.Value != null) DirectShowUtil.ReleaseComObject(ppFilter.Value, 5000); } PostProcessFilterAudio.Clear(); Log.Info("BDPlayer: Cleanup PostProcessAudio"); } #endregion if (_interfaceBDReader != null) { DirectShowUtil.ReleaseComObject(_interfaceBDReader, 5000); _interfaceBDReader = null; } if (_graphBuilder != null) { DirectShowUtil.RemoveFilters(_graphBuilder); if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } while ((hr = DirectShowUtil.ReleaseComObject(_graphBuilder)) > 0) ; _graphBuilder = null; } if (_dvbSubRenderer != null) { _dvbSubRenderer.SetPlayer(null); _dvbSubRenderer = null; } if (_vmr9 != null) { _vmr9.SafeDispose(); _vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; } catch (Exception ex) { Log.Error("BDPlayer: Exception while cleaning DShow graph - {0} {1}", ex.Message, ex.StackTrace); } //switch back to directx windowed mode ExclusiveMode(false); }
private void Run() { if (this.fmc == null) return; IGraphBuilder igb = (IGraphBuilder)this.fmc; try { // tell the graph builder about the filter graph this.icgb.SetFiltergraph(igb); igb.AddFilter(this.sf, "Video Capture"); igb.AddFilter(this.sgf, "Sample Grabber"); this.icgb.RenderStream(ref PIN_CATEGORY_CAPTURE, ref MEDIATYPE_Video, this.sf, this.sgf, null); // access different interfaces, ask runtime to notify this window this.ime = (IMediaEventEx)this.fmc; this.ime.SetNotifyWindow((int)this.Handle, WM_GRAPHNOTIFY, 0); // sets the video owner and style of this window this.ivw = (IVideoWindow)this.fmc; this.ivw.Owner = (int)this.Handle; this.ivw.WindowStyle = WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; ivw.SetWindowPosition(this.ClientRectangle.Left, this.ClientRectangle.Top, this.ClientRectangle.Width, this.ClientSize.Height - this.btnCapture.Height - vertical_space); // get the ball rolling this.fmc.Run(); } catch (Exception ex) { Cleanup(false); MessageBox.Show("Couldn't run: " + ex.Message); } }
public override void Initialize(Control ownerControl, string videoFileName, EventHandler onVideoLoaded, EventHandler onVideoEnded) { const int wsChild = 0x40000000; string ext = System.IO.Path.GetExtension(videoFileName).ToLower(); bool isAudio = ext == ".mp3" || ext == ".wav" || ext == ".wma" || ext == ".ogg" || ext == ".mpa" || ext == ".m4a" || ext == ".ape" || ext == ".aiff" || ext == ".flac" || ext == ".acc" || ext == ".mka"; OnVideoLoaded = onVideoLoaded; OnVideoEnded = onVideoEnded; VideoFileName = videoFileName; _owner = ownerControl; _quartzFilgraphManager = new FilgraphManager(); _quartzFilgraphManager.RenderFile(VideoFileName); if (!isAudio) { _quartzVideo = _quartzFilgraphManager as IVideoWindow; _quartzVideo.Owner = (int)ownerControl.Handle; _quartzVideo.SetWindowPosition(0, 0, ownerControl.Width, ownerControl.Height); _quartzVideo.WindowStyle = wsChild; } //Play(); if (!isAudio) (_quartzFilgraphManager as IBasicVideo).GetVideoSize(out _sourceWidth, out _sourceHeight); _owner.Resize += OwnerControlResize; _mediaPosition = (IMediaPosition)_quartzFilgraphManager; if (OnVideoLoaded != null) { _videoLoader = new BackgroundWorker(); _videoLoader.RunWorkerCompleted += VideoLoaderRunWorkerCompleted; _videoLoader.DoWork += VideoLoaderDoWork; _videoLoader.RunWorkerAsync(); } OwnerControlResize(this, null); _videoEndTimer = new Timer { Interval = 500 }; _videoEndTimer.Tick += VideoEndTimerTick; _videoEndTimer.Start(); if (!isAudio) _quartzVideo.MessageDrain = (int)ownerControl.Handle; }
// Configure the video window private void ConfigureVideoWindow(IVideoWindow videoWindow, Control hWin) { int hr; // Set the output window hr = videoWindow.put_Owner(hWin.Handle); DsError.ThrowExceptionForHR(hr); // Set the window style hr = videoWindow.put_WindowStyle((WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings)); DsError.ThrowExceptionForHR(hr); // Make the window visible hr = videoWindow.put_Visible(OABool.True); DsError.ThrowExceptionForHR(hr); // Position the playing location Rectangle rc = hWin.ClientRectangle; hr = videoWindow.SetWindowPosition(0, 0, rc.Right, rc.Bottom); DsError.ThrowExceptionForHR(hr); }
public void CloseInterfaces() { // Stop previewing data if (this.mediaControl != null) this.mediaControl.StopWhenReady(); this.currentState = PlayState.Stopped; // Stop receiving events if (this.mediaEventEx != null) this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); // Relinquish ownership (IMPORTANT!) of the video window. // Failing to call put_Owner can lead to assert failures within // the video renderer, as it still assumes that it has a valid // parent window. if(this.videoWindow != null) { this.videoWindow.put_Visible(OABool.False); this.videoWindow.put_Owner(IntPtr.Zero); } // Remove filter graph from the running object table if (rot != null) { rot.Dispose(); rot = null; } // Release DirectShow interfaces Marshal.ReleaseComObject(this.mediaControl); this.mediaControl = null; Marshal.ReleaseComObject(this.mediaEventEx); this.mediaEventEx = null; Marshal.ReleaseComObject(this.videoWindow); this.videoWindow = null; Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null; Marshal.ReleaseComObject(this.captureGraphBuilder); this.captureGraphBuilder = null; }
/* // Uncomment this version of FindCaptureDevice to use the DsDevice helper class // (and comment the first version of course) public IBaseFilter FindCaptureDevice() { System.Collections.ArrayList devices; object source; // Get all video input devices devices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); // Take the first device DsDevice device = (DsDevice)devices[0]; // Bind Moniker to a filter object Guid iid = typeof(IBaseFilter).GUID; device.Mon.BindToObject(null, null, ref iid, out source); // An exception is thrown if cast fail return (IBaseFilter) source; } */ public void GetInterfaces() { int hr = 0; // An exception is thrown if cast fail this.graphBuilder = (IGraphBuilder) new FilterGraph(); this.captureGraphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); this.mediaControl = (IMediaControl) this.graphBuilder; this.videoWindow = (IVideoWindow) this.graphBuilder; this.mediaEventEx = (IMediaEventEx) this.graphBuilder; hr = this.mediaEventEx.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); }
private void PlayMovieInWindow(string filename) { int hr = 0; if (filename == string.Empty) return; this.graphBuilder = (IGraphBuilder) new FilterGraph(); // Have the graph builder construct its the appropriate graph automatically hr = this.graphBuilder.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); // 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 = this.graphBuilder as IVideoWindow; this.basicVideo = this.graphBuilder as IBasicVideo; // Query for audio interfaces, which may not be relevant for video-only files this.basicAudio = this.graphBuilder as IBasicAudio; // Is this an audio-only file (no video component)? CheckVisibility(); // Have the graph signal event via window callbacks for performance hr = this.mediaEventEx.SetNotifyWindow(this.Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); if (!this.isAudioOnly) { // Setup the video window hr = this.videoWindow.put_Owner(this.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); hr = InitVideoWindow(1, 1); DsError.ThrowExceptionForHR(hr); GetFrameStepInterface(); } else { // Initialize the default player size and enable playback menu items hr = InitPlayerWindow(); DsError.ThrowExceptionForHR(hr); EnablePlaybackMenu(true, MediaType.Audio); } // Complete window initialization CheckSizeMenu(menuFileSizeNormal); this.isFullScreen = false; this.currentPlaybackRate = 1.0; UpdateMainTitle(); #if DEBUG rot = new DsROTEntry(this.graphBuilder); #endif this.Focus(); // Run the graph to play the media file hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); this.currentState=PlayState.Running; }
/// <summary> /// Connects the filters of a previously created graph /// (created by createGraph()). Once rendered the graph /// is ready to be used. This method may also destroy /// streams if we have streams we no longer want. /// </summary> protected void renderGraph() { Guid cat; Guid med; int hr; bool didSomething = false; #if DSHOWNET const int WS_CHILD = 0x40000000; const int WS_CLIPCHILDREN = 0x02000000; const int WS_CLIPSIBLINGS = 0x04000000; #endif assertStopped(); // Ensure required properties set if ( filename == null ) throw new ArgumentException( "The Filename property has not been set to a file.\n" ); // Stop the graph if ( mediaControl != null ) mediaControl.Stop(); // Create the graph if needed (group should already be created) createGraph(); // Derender the graph if we have a capture or preview stream // that we no longer want. We can't derender the capture and // preview streams seperately. // Notice the second case will leave a capture stream intact // even if we no longer want it. This allows the user that is // not using the preview to Stop() and Start() without // rerendering the graph. if ( !wantPreviewRendered && isPreviewRendered ) derenderGraph(); if ( !wantCaptureRendered && isCaptureRendered ) if ( wantPreviewRendered ) derenderGraph(); // Render capture stream (only if necessary) if ( wantCaptureRendered && !isCaptureRendered ) { // Render the file writer portion of graph (mux -> file) // Record captured audio/video in Avi, Wmv or Wma format Guid mediaSubType; // Media sub type bool captureAudio = true; bool captureVideo = true; IBaseFilter videoCompressorfilter = null; // Set media sub type and video compressor filter if needed if(RecFileMode == RecFileModeType.Avi) { mediaSubType = MediaSubType.Avi; // For Avi file saving a video compressor must be used // If one is selected, that one will be used. videoCompressorfilter = videoCompressorFilter; } else { mediaSubType = MediaSubType.Asf; } // Intialize the Avi or Asf file writer #if DSHOWNET hr = captureGraphBuilder.SetOutputFileName(ref mediaSubType, Filename, out muxFilter, out fileWriterFilter); #else hr = captureGraphBuilder.SetOutputFileName(mediaSubType, Filename, out muxFilter, out fileWriterFilter); #endif if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); // For Wma (and Wmv) a suitable profile must be selected. This // can be done via a property window, however the muxFilter is // just created. if needed, the property windows should show up // right now! // Another solution is to configure the Asf file writer, the // use interface must ensure the proper format has been // selected. if((RecFileMode == RecFileModeType.Wma)|| (RecFileMode == RecFileModeType.Wmv)) { if(this.AsfFormat != null) { this.AsfFormat.UpdateAsfAVFormat(this.muxFilter); this.AsfFormat.GetCurrentAsfAVInfo(out captureAudio, out captureVideo); } } // Render video (video -> mux) if needed or possible if((VideoDevice != null)&&(captureVideo)) { // Try interleaved first, because if the device supports it, // it's the only way to get audio as well as video cat = PinCategory.Capture; med = MediaType.Interleaved; #if DSHOWNET hr = captureGraphBuilder.RenderStream(ref cat, ref med, videoDeviceFilter, videoCompressorfilter, muxFilter); #else hr = captureGraphBuilder.RenderStream( DsGuid.FromGuid(cat), DsGuid.FromGuid(med), videoDeviceFilter, videoCompressorFilter, muxFilter ); #endif if( hr < 0 ) { med = MediaType.Video; #if DSHOWNET hr = captureGraphBuilder.RenderStream(ref cat, ref med, videoDeviceFilter, videoCompressorfilter, muxFilter); #else hr = captureGraphBuilder.RenderStream( DsGuid.FromGuid(cat), DsGuid.FromGuid(med), videoDeviceFilter, videoCompressorFilter, muxFilter ); #endif if ( hr == -2147220969 ) throw new DeviceInUseException( "Video device", hr ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); } } // Render audio (audio -> mux) if possible if((audioDeviceFilter != null)&&(captureAudio)) { // If this Asf file format than please keep in mind that // certain Wmv formats do not have an audio stream, so // when using this code, please ensure you use a format // which supports audio! cat = PinCategory.Capture; med = MediaType.Audio; #if DSHOWNET hr = captureGraphBuilder.RenderStream( ref cat, ref med, audioDeviceFilter, audioCompressorFilter, muxFilter ); #else hr = captureGraphBuilder.RenderStream( DsGuid.FromGuid(cat), DsGuid.FromGuid(med), audioDeviceFilter, audioCompressorFilter, muxFilter ); #endif if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); } else if( (this.AudioViaPci)&&(captureAudio)&& (audioDeviceFilter == null)&&(videoDeviceFilter != null) ) { cat = PinCategory.Capture; med = MediaType.Audio; #if DSHOWNET hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, audioCompressorFilter, muxFilter ); #else hr = captureGraphBuilder.RenderStream(cat, med, videoDeviceFilter, audioCompressorFilter, muxFilter); #endif if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); } isCaptureRendered = true; didSomething = true; } // Render preview stream (only if necessary) if ( wantPreviewRendered && !isPreviewRendered ) { // Render preview (video -> renderer) this.InitVideoRenderer(); this.AddDeInterlaceFilter(); // When capture pin is used, preview works immediately, // however this conflicts with file saving. // An alternative is to use VMR9 cat = PinCategory.Preview; med = MediaType.Video; // #if NEWCODE if(this.InitSampleGrabber()) { Debug.WriteLine("SampleGrabber added to graph."); #if DSHOWNET hr = captureGraphBuilder.RenderStream(ref cat, ref med, videoDeviceFilter, this.baseGrabFlt, this.videoRendererFilter); #else hr = captureGraphBuilder.RenderStream(DsGuid.FromGuid(cat), DsGuid.FromGuid(med), videoDeviceFilter, this.baseGrabFlt, this.videoRendererFilter); #endif if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); } else // #endif NEWCODE { #if DSHOWNET hr = captureGraphBuilder.RenderStream(ref cat, ref med, videoDeviceFilter, null, this.videoRendererFilter); #else hr = captureGraphBuilder.RenderStream(DsGuid.FromGuid(cat), DsGuid.FromGuid(med), videoDeviceFilter, null, this.videoRendererFilter); #endif if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); } // Special option to enable rendering audio via PCI bus if((this.AudioViaPci)&&(audioDeviceFilter != null)) { cat = PinCategory.Preview; med = MediaType.Audio; #if DSHOWNET hr = captureGraphBuilder.RenderStream( ref cat, ref med, audioDeviceFilter, null, null ); #else hr = captureGraphBuilder.RenderStream(DsGuid.FromGuid(cat), DsGuid.FromGuid(med), audioDeviceFilter, null, null); #endif if( hr < 0 ) { Marshal.ThrowExceptionForHR( hr ); } } else if( (this.AudioViaPci)&& (this.audioDeviceFilter == null)&&(this.videoDeviceFilter != null) ) { cat = PinCategory.Preview; med = MediaType.Audio; #if DSHOWNET hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, null, null ); #else hr = captureGraphBuilder.RenderStream(cat, med, videoDeviceFilter, null, null); #endif if( hr < 0 ) { Marshal.ThrowExceptionForHR( hr ); } } // Get the IVideoWindow interface videoWindow = (IVideoWindow) graphBuilder; // Set the video window to be a child of the main window hr = videoWindow.put_Owner( previewWindow.Handle ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); // Set video window style #if DSHOWNET hr = videoWindow.put_WindowStyle( WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS); #else hr = videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings); #endif if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); // Position video window in client rect of owner window previewWindow.Resize += new EventHandler( onPreviewWindowResize ); onPreviewWindowResize( this, null ); // Make the video window visible, now that it is properly positioned #if DSHOWNET hr = videoWindow.put_Visible( DsHlp.OATRUE ); #else hr = videoWindow.put_Visible( OABool.True ); #endif if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); isPreviewRendered = true; didSomething = true; // #if NEWCODE SetMediaSampleGrabber(); // #endif NEWCODE } if ( didSomething ) graphState = GraphState.Rendered; }