private void BuildGraph(string fileName) { int hr = 0; try { graphBuilder = (IFilterGraph2)new FilterGraph(); mediaControl = (IMediaControl)graphBuilder; mediaSeeking = (IMediaSeeking)graphBuilder; mediaPosition = (IMediaPosition)graphBuilder; vmr9 = (IBaseFilter)new VideoMixingRenderer9(); ConfigureVMR9InWindowlessMode(); hr = graphBuilder.AddFilter(vmr9, "Video Mixing Renderer 9"); DsError.ThrowExceptionForHR(hr); hr = graphBuilder.RenderFile(fileName, null); DsError.ThrowExceptionForHR(hr); } catch (Exception e) { CloseInterfaces(); MessageBox.Show("An error occured during the graph building : \r\n\r\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//TODO Fichier déjà utilisé.... surement par Quartz. Essayer de libérer les ressources de la librairie public void Play(Guid id, byte[] file) { objFilterGraph = new FilgraphManager(); audio = (IBasicAudio) objFilterGraph; //pb d'accès concurrenciel string path = ConfigurationManager.AppSettings["MediaCache"] + id + ".mp3"; File.WriteAllBytes(path, file); objFilterGraph.RenderFile(path); objMediaPosition = objFilterGraph as IMediaPosition; objFilterGraph.Run(); tmProgressionFlux = new Timer(1000) { Enabled = true }; tmProgressionFlux.Elapsed += TmProgressionFluxTick; TimerResume(); }
//Метод 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; }
// Methods internal AudioAnimate(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc) { this.m_objFilterGraph = null; this.m_objBasicAudio = null; this.m_objMediaEvent = null; this.m_objMediaEventEx = null; this.m_objMediaPosition = null; this.m_objMediaControl = null; this.fillColor = Color.Khaki; this.fileName = string.Empty; this.m_CurrentStatus = MediaStatus.None; this.timer = new Timer(); this.oldtime = 0f; this.timertime = 0f; this.timer.Interval = 100; this.timer.Tick += new EventHandler(this.TimerTick); }
/// <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(); }
/** * 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; }
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> 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; } }
private void openMedia() { openFileDialog1.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*"; if (DialogResult.OK == openFileDialog1.ShowDialog()) { CleanUp(); m_objFilterGraph = new FilgraphManager(); m_objFilterGraph.RenderFile(openFileDialog1.FileName); m_objBasicAudio = m_objFilterGraph as IBasicAudio; try { m_objVideoWindow = m_objFilterGraph as IVideoWindow; m_objVideoWindow.Owner = (int)panel1.Handle; m_objVideoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN; m_objVideoWindow.SetWindowPosition(panel1.ClientRectangle.Left, panel1.ClientRectangle.Top, panel1.ClientRectangle.Width, panel1.ClientRectangle.Height); } catch(Exception) { 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; this.Text = "Whistle- " + openFileDialog1.FileName + "]"; m_objMediaControl.Run(); m_CurrentStatus = MediaStatus.Running; } }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here if(fileName != null){ graphManager.RenderFile(fileName); mControl = graphManager; mPosition = graphManager; mPosition.Rate = 1.0f; mWindow = graphManager; mWindow.Owner = Window.Handle.ToInt32(); mWindow.WindowStyle = WS_CHILD; mWindow.SetWindowPosition(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height); graphManager.Run(); System.Diagnostics.Debug.WriteLine( graphManager.SourceHeight); System.Diagnostics.Debug.WriteLine( graphManager.SourceWidth); } oldState = Keyboard.GetState(); }
private void ClosePlayback() { int hr = 0; try { 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 { } }
public override void Init() { if (!isPlaying) { string Filename = ""; float size = 0; double Max = 0; int volume = 0; graph = new FilterGraph() as IFilterGraph; media = graph as IMediaControl; eventEx = media as IMediaEventEx; igb = media as IGraphBuilder; imp = igb as IMediaPosition; master.form.Invoke((MethodInvoker)delegate() { Filename = master.form.M_Filename.Text; media.RenderFile(Filename); size = (float)master.form.M_PrevSize.Value; master.form.M_PrevSize.Enabled = false; imp.get_Duration(out Max); master.form.M_Seek.Maximum = (int)(Max); master.form.M_Seek.Value = 0; volume = master.form.M_Volume.Value; span = (uint)(1000000.0f / master.form.M_CollectFPS); }); graph.FindFilterByName("Video Renderer", out render); if (render != null) { window = render as IVideoWindow; window.put_WindowStyle( WindowStyle.Caption | WindowStyle.Child ); window.put_WindowStyleEx( WindowStyleEx.ToolWindow ); window.put_Caption("ElectronicBoard - VideoPrev -"); int Width, Height, Left, Top; window.get_Width(out Width); window.get_Height(out Height); window.get_Left(out Left); window.get_Top(out Top); renderSize.Width = (int)(Width * size); renderSize.Height = (int)(Height * size); Aspect = (float)renderSize.Height / (float)renderSize.Width; window.SetWindowPosition(Left, Top, renderSize.Width, renderSize.Height); eventEx = media as IMediaEventEx; eventEx.SetNotifyWindow(master.form.Handle, WM_DirectShow, IntPtr.Zero); media.Run(); foreach (Process p in Process.GetProcesses()) { if (p.MainWindowTitle == "ElectronicBoard - VideoPrev -") { renderwindow = p.MainWindowHandle; break; } } isPlaying = true; iba = media as IBasicAudio; iba.put_Volume(volume); //master.form.checkBox3_CheckedChanged(null, null); master.Start(); } } }
private void Cleanup() { if (graphBuilder == null || (VMR9Util.g_vmr9 != null && VMR9Util.g_vmr9.isCurrentStopping)) { 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) { if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.RestoreGuiForMadVr(); VMR9Util.g_vmr9.SafeDispose(); } 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); }
/// <summary> /// Initialises DirectShow interfaces /// </summary> private void InitInterfaces() { var comtype = Type.GetTypeFromCLSID(Clsid.FilterGraph); if (comtype == null) throw new NotSupportedException("DirectX (8.1 or higher) not installed?"); var fg = Activator.CreateInstance(comtype); m_graphBuilder = (IGraphBuilder)fg; m_mediaControl = (IMediaControl)fg; m_mediaEvent = (IMediaEventEx)fg; m_mediaSeeking = (IMediaSeeking)fg; m_mediaPosition = (IMediaPosition)fg; m_basicAudio = (IBasicAudio)fg; fg = null; }
private void StartCapture() { int hr; ISampleGrabber sampGrabber = null; IBaseFilter capFilter = null; ICaptureGraphBuilder2 capGraph = null; if (System.IO.File.Exists(txtAviFileName.Text)) { // Get the graphbuilder object m_FilterGraph = (IFilterGraph2) new FilterGraph(); m_mediaCtrl = m_FilterGraph as IMediaControl; // Get the ICaptureGraphBuilder2 capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); // Get the SampleGrabber interface sampGrabber = (ISampleGrabber) new SampleGrabber(); // Start building the graph hr = capGraph.SetFiltergraph(m_FilterGraph); DsError.ThrowExceptionForHR(hr); // Add the video source hr = m_FilterGraph.AddSourceFilter(txtAviFileName.Text, "File Source (Async.)", out capFilter); DsError.ThrowExceptionForHR(hr); //add AVI Decompressor IBaseFilter pAVIDecompressor = (IBaseFilter) new AVIDec(); hr = m_FilterGraph.AddFilter(pAVIDecompressor, "AVI Decompressor"); DsError.ThrowExceptionForHR(hr); IBaseFilter ffdshow; try { // Create Decoder filter COM object (ffdshow video decoder) Type comtype = Type.GetTypeFromCLSID(new Guid("{04FE9017-F873-410E-871E-AB91661A4EF7}")); if (comtype == null) { throw new NotSupportedException("Creating ffdshow video decoder COM object fails."); } object comobj = Activator.CreateInstance(comtype); ffdshow = (IBaseFilter)comobj; // error ocurrs! raised exception comobj = null; } catch { CustomMessageBox.Show("Please install/reinstall ffdshow"); return; } hr = m_FilterGraph.AddFilter(ffdshow, "ffdshow"); DsError.ThrowExceptionForHR(hr); // IBaseFilter baseGrabFlt = (IBaseFilter)sampGrabber; ConfigureSampleGrabber(sampGrabber); // Add the frame grabber to the graph hr = m_FilterGraph.AddFilter(baseGrabFlt, "Ds.NET Grabber"); DsError.ThrowExceptionForHR(hr); IBaseFilter vidrender = (IBaseFilter) new VideoRenderer(); hr = m_FilterGraph.AddFilter(vidrender, "Render"); DsError.ThrowExceptionForHR(hr); IPin captpin = DsFindPin.ByDirection(capFilter, PinDirection.Output, 0); IPin ffdpinin = DsFindPin.ByName(ffdshow, "In"); IPin ffdpinout = DsFindPin.ByName(ffdshow, "Out"); IPin samppin = DsFindPin.ByName(baseGrabFlt, "Input"); hr = m_FilterGraph.Connect(captpin, ffdpinin); DsError.ThrowExceptionForHR(hr); hr = m_FilterGraph.Connect(ffdpinout, samppin); DsError.ThrowExceptionForHR(hr); FileWriter filewritter = new FileWriter(); IFileSinkFilter filemux = (IFileSinkFilter)filewritter; //filemux.SetFileName("test.avi",); //hr = capGraph.RenderStream(null, MediaType.Video, capFilter, null, vidrender); // DsError.ThrowExceptionForHR(hr); SaveSizeInfo(sampGrabber); // setup buffer if (m_handle == IntPtr.Zero) { m_handle = Marshal.AllocCoTaskMem(m_stride * m_videoHeight); } // tell the callback to ignore new images m_PictureReady = new ManualResetEvent(false); m_bGotOne = false; m_bRunning = false; timer1 = new Thread(timer); timer1.IsBackground = true; timer1.Start(); m_mediaextseek = m_FilterGraph as IAMExtendedSeeking; m_mediapos = m_FilterGraph as IMediaPosition; m_mediaseek = m_FilterGraph as IMediaSeeking; double length = 0; m_mediapos.get_Duration(out length); trackBar_mediapos.Minimum = 0; trackBar_mediapos.Maximum = (int)length; Start(); } else { MessageBox.Show("File does not exist"); } }
/// <summary> create the used COM components and get the interfaces. </summary> protected bool GetInterfaces() { VMR9Util.g_vmr9 = null; if (IsRadio == false) { Vmr9 = VMR9Util.g_vmr9 = new VMR9Util(); // switch back to directx fullscreen mode Log.Info("RTSPPlayer: Enabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 1, 0, null); GUIWindowManager.SendMessage(msg); } //Type comtype = null; //object comobj = null; DsRect rect = new DsRect(); rect.top = 0; rect.bottom = GUIGraphicsContext.form.Height; rect.left = 0; rect.right = GUIGraphicsContext.form.Width; try { graphBuilder = (IGraphBuilder) new FilterGraph(); Log.Info("RTSPPlayer: add source filter"); if (IsRadio == false) { bool AddVMR9 = VMR9Util.g_vmr9 != null && VMR9Util.g_vmr9.AddVMR9(graphBuilder); if (!AddVMR9) { Log.Error("RTSPPlayer:Failed to add VMR9 to graph"); return(false); } VMR9Util.g_vmr9.Enable(false); } _mpegDemux = (IBaseFilter) new MPEG2Demultiplexer(); graphBuilder.AddFilter(_mpegDemux, "MPEG-2 Demultiplexer"); _rtspSource = (IBaseFilter) new RtpSourceFilter(); int hr = graphBuilder.AddFilter((IBaseFilter)_rtspSource, "RTSP Source Filter"); if (hr != 0) { Log.Error("RTSPPlayer:unable to add RTSP source filter:{0:X}", hr); return(false); } // add preferred video & audio codecs Log.Info("RTSPPlayer: add video/audio codecs"); string strVideoCodec = ""; string strAudioCodec = ""; string strAudiorenderer = ""; int intFilters = 0; // FlipGer: count custom filters string strFilters = ""; // FlipGer: collect custom filters string postProcessingFilterSection = "mytv"; using (Settings xmlreader = new MPSettings()) { if (_mediaType == g_Player.MediaType.Video) { strVideoCodec = xmlreader.GetValueAsString("movieplayer", "mpeg2videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("movieplayer", "mpeg2audiocodec", ""); strAudiorenderer = xmlreader.GetValueAsString("movieplayer", "audiorenderer", "Default DirectSound Device"); postProcessingFilterSection = "movieplayer"; } else { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", ""); strAudiorenderer = xmlreader.GetValueAsString("mytv", "audiorenderer", "Default DirectSound Device"); postProcessingFilterSection = "mytv"; } enableDvbSubtitles = xmlreader.GetValueAsBool("tvservice", "dvbsubtitles", false); // FlipGer: load infos for custom filters int intCount = 0; while (xmlreader.GetValueAsString(postProcessingFilterSection, "filter" + intCount.ToString(), "undefined") != "undefined") { if (xmlreader.GetValueAsBool(postProcessingFilterSection, "usefilter" + intCount.ToString(), false)) { strFilters += xmlreader.GetValueAsString(postProcessingFilterSection, "filter" + intCount.ToString(), "undefined") + ";"; intFilters++; } intCount++; } } string extension = Path.GetExtension(m_strCurrentFile).ToLowerInvariant(); if (IsRadio == false) { if (strVideoCodec.Length > 0) { DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); } } if (strAudioCodec.Length > 0) { DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); } if (enableDvbSubtitles == true) { try { _subtitleFilter = SubtitleRenderer.GetInstance().AddSubtitleFilter(graphBuilder); SubtitleRenderer.GetInstance().SetPlayer(this); dvbSubRenderer = SubtitleRenderer.GetInstance(); } catch (Exception e) { Log.Error(e); } } Log.Debug("Is subtitle fitler null? {0}", (_subtitleFilter == null)); // FlipGer: add custom filters to graph string[] arrFilters = strFilters.Split(';'); for (int i = 0; i < intFilters; i++) { DirectShowUtil.AddFilterToGraph(graphBuilder, arrFilters[i]); } if (strAudiorenderer.Length > 0) { audioRendererFilter = DirectShowUtil.AddAudioRendererToGraph(graphBuilder, strAudiorenderer, false); } Log.Info("RTSPPlayer: load:{0}", m_strCurrentFile); IFileSourceFilter interfaceFile = (IFileSourceFilter)_rtspSource; if (interfaceFile == null) { Log.Error("RTSPPlayer:Failed to get IFileSourceFilter"); return(false); } //Log.Info("RTSPPlayer: open file:{0}",filename); hr = interfaceFile.Load(m_strCurrentFile, null); if (hr != 0) { Log.Error("RTSPPlayer:Failed to open file:{0} :0x{1:x}", m_strCurrentFile, hr); return(false); } #region connect rtspsource->demux Log.Info("RTSPPlayer:connect rtspsource->mpeg2 demux"); IPin pinTsOut = DsFindPin.ByDirection((IBaseFilter)_rtspSource, PinDirection.Output, 0); if (pinTsOut == null) { Log.Info("RTSPPlayer:failed to find output pin of tsfilesource"); return(false); } IPin pinDemuxIn = DsFindPin.ByDirection(_mpegDemux, PinDirection.Input, 0); if (pinDemuxIn == null) { Log.Info("RTSPPlayer:failed to find output pin of tsfilesource"); return(false); } hr = graphBuilder.Connect(pinTsOut, pinDemuxIn); if (hr != 0) { Log.Info("RTSPPlayer:failed to connect rtspsource->mpeg2 demux:{0:X}", hr); return(false); } DirectShowUtil.ReleaseComObject(pinTsOut); DirectShowUtil.ReleaseComObject(pinDemuxIn); #endregion #region render demux output pins if (IsRadio) { Log.Info("RTSPPlayer:render audio demux outputs"); IEnumPins enumPins; _mpegDemux.EnumPins(out enumPins); IPin[] pins = new IPin[2]; int fetched = 0; while (enumPins.Next(1, pins, out fetched) == 0) { if (fetched != 1) { break; } PinDirection direction; pins[0].QueryDirection(out direction); if (direction == PinDirection.Input) { continue; } IEnumMediaTypes enumMediaTypes; pins[0].EnumMediaTypes(out enumMediaTypes); AMMediaType[] mediaTypes = new AMMediaType[20]; int fetchedTypes; enumMediaTypes.Next(20, mediaTypes, out fetchedTypes); for (int i = 0; i < fetchedTypes; ++i) { if (mediaTypes[i].majorType == MediaType.Audio) { graphBuilder.Render(pins[0]); break; } } } } else { Log.Info("RTSPPlayer:render audio/video demux outputs"); IEnumPins enumPins; _mpegDemux.EnumPins(out enumPins); IPin[] pins = new IPin[2]; int fetched = 0; while (enumPins.Next(1, pins, out fetched) == 0) { if (fetched != 1) { break; } PinDirection direction; pins[0].QueryDirection(out direction); if (direction == PinDirection.Input) { continue; } graphBuilder.Render(pins[0]); } } #endregion // Connect DVB subtitle filter pins in the graph if (_mpegDemux != null && enableDvbSubtitles == true) { IMpeg2Demultiplexer demuxer = _mpegDemux as IMpeg2Demultiplexer; hr = demuxer.CreateOutputPin(GetTSMedia(), "Pcr", out _pinPcr); if (hr == 0) { Log.Info("RTSPPlayer:_pinPcr OK"); IPin pDemuxerPcr = DsFindPin.ByName(_mpegDemux, "Pcr"); IPin pSubtitlePcr = DsFindPin.ByName(_subtitleFilter, "Pcr"); hr = graphBuilder.Connect(pDemuxerPcr, pSubtitlePcr); } else { Log.Info("RTSPPlayer:Failed to create _pinPcr in demuxer:{0:X}", hr); } hr = demuxer.CreateOutputPin(GetTSMedia(), "Subtitle", out _pinSubtitle); if (hr == 0) { Log.Info("RTSPPlayer:_pinSubtitle OK"); IPin pDemuxerSubtitle = DsFindPin.ByName(_mpegDemux, "Subtitle"); IPin pSubtitle = DsFindPin.ByName(_subtitleFilter, "In"); hr = graphBuilder.Connect(pDemuxerSubtitle, pSubtitle); } else { Log.Info("RTSPPlayer:Failed to create _pinSubtitle in demuxer:{0:X}", hr); } hr = demuxer.CreateOutputPin(GetTSMedia(), "PMT", out _pinPMT); if (hr == 0) { Log.Info("RTSPPlayer:_pinPMT OK"); IPin pDemuxerSubtitle = DsFindPin.ByName(_mpegDemux, "PMT"); IPin pSubtitle = DsFindPin.ByName(_subtitleFilter, "PMT"); hr = graphBuilder.Connect(pDemuxerSubtitle, pSubtitle); } else { Log.Info("RTSPPlayer:Failed to create _pinPMT in demuxer:{0:X}", hr); } } if (IsRadio == false) { if (!VMR9Util.g_vmr9.IsVMR9Connected) { //VMR9 is not supported, switch to overlay Log.Info("RTSPPlayer: vmr9 not connected"); _mediaCtrl = null; Cleanup(); return(false); } VMR9Util.g_vmr9.SetDeinterlaceMode(); } _mediaCtrl = (IMediaControl)graphBuilder; mediaEvt = (IMediaEventEx)graphBuilder; _mediaSeeking = (IMediaSeeking)graphBuilder; mediaPos = (IMediaPosition)graphBuilder; basicAudio = graphBuilder as IBasicAudio; //DirectShowUtil.SetARMode(graphBuilder,AspectRatioMode.Stretched); DirectShowUtil.EnableDeInterlace(graphBuilder); if (VMR9Util.g_vmr9 != null) { m_iVideoWidth = VMR9Util.g_vmr9.VideoWidth; m_iVideoHeight = VMR9Util.g_vmr9.VideoHeight; } if (audioRendererFilter != null) { Log.Info("RTSPPlayer9:set reference clock"); IMediaFilter mp = graphBuilder as IMediaFilter; IReferenceClock clock = audioRendererFilter as IReferenceClock; hr = mp.SetSyncSource(null); hr = mp.SetSyncSource(clock); Log.Info("RTSPPlayer9:set reference clock:{0:X}", hr); } Log.Info("RTSPPlayer: graph build successfull"); return(true); } catch (Exception ex) { Error.SetError("Unable to play movie", "Unable build graph for VMR9"); Log.Error("RTSPPlayer:exception while creating DShow graph {0} {1}", ex.Message, ex.StackTrace); CloseInterfaces(); return(false); } }
/// <summary>Load a video/audio file and prepare to play it</summary> public void LoadFile(string file) { try { if (m_filter_graph != null) { throw new Exception("Reusing this Video object is not allowed"); } m_file = file; m_filter_graph = new FilterGraph() as IFilterGraph2; if (m_filter_graph == null) { throw new Exception("failed to create direct show filter graph"); } // Have the filter graph construct the appropriate graph automatically DsError.ThrowExceptionForHR(m_filter_graph.RenderFile(file, null)); #if DEBUG // Allows you to view the graph with GraphEdit File/Connect m_ds_rot = new DsROTEntry(m_filter_graph); #endif // Grab some other interfaces m_media_event = m_filter_graph as IMediaEvent; m_media_ctrl = m_filter_graph as IMediaControl; m_media_position = m_filter_graph as IMediaPosition; if (m_media_event == null) { throw new Exception("failed to obtain a direct show IMediaEvent interface"); } if (m_media_ctrl == null) { throw new Exception("failed to obtain a direct show IMediaControl interface"); } if (m_media_position == null) { throw new Exception("failed to obtain a direct show IMediaPosition interface"); } // Grab optional interfaces m_video_window = m_filter_graph as IVideoWindow; m_basic_video = m_filter_graph as IBasicVideo; m_basic_audio = m_filter_graph as IBasicAudio; // If this is an audio-only clip, get_Visible() won't work. Also, if this // video is encoded with an unsupported codec, we won't see any video, // although the audio will work if it is of a supported format. if (m_video_window != null) { const int E_NOINTERFACE = unchecked ((int)0x80004002); // Use put Visible since we want to hide the video window // till we're ready to show it anyway int hr = m_video_window.put_Visible(OABool.False); if (hr == E_NOINTERFACE) { m_video_window = null; } else { DsError.ThrowExceptionForHR(hr); } } // Get the event handle the graph will use to signal when events occur, wrap it in a ManualResetEvent IntPtr media_event; DsError.ThrowExceptionForHR(m_media_event.GetEventHandle(out media_event)); m_event = new ManualResetEvent(false) { SafeWaitHandle = new SafeWaitHandle(media_event, false) }; // Create a new thread to wait for events m_media_event_thread = new Thread(MediaEventWait) { Name = "Media Event Thread" }; m_media_event_thread.Start(); if (FileLoaded != null) { FileLoaded(this, file); } } catch { Dispose(); throw; } #if DEBUG GC.Collect(); // Double check to make sure we aren't releasing something important. GC.WaitForPendingFinalizers(); #endif }
public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard) { try { if (!Supports(format)) { return(false); } string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLowerInvariant() != ".ts" && ext.ToLowerInvariant() != ".mpg") { Log.Info("TSReader2WMV: wrong file format"); return(false); } Log.Info("TSReader2WMV: create graph"); graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("TSReader2WMV: add filesource"); TsReader reader = new TsReader(); tsreaderSource = (IBaseFilter)reader; //ITSReader ireader = (ITSReader)reader; //ireader.SetTsReaderCallback(this); //ireader.SetRequestAudioChangeCallback(this); IBaseFilter filter = (IBaseFilter)tsreaderSource; graphBuilder.AddFilter(filter, "TSReader Source"); IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource; Log.Info("TSReader2WMV: load file:{0}", info.file); int hr = fileSource.Load(info.file, null); //add audio/video codecs string strVideoCodec = ""; string strH264VideoCodec = ""; string strAudioCodec = ""; string strAACAudioCodec = ""; using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings()) { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", ""); strAACAudioCodec = xmlreader.GetValueAsString("mytv", "aacaudiocodec", ""); strH264VideoCodec = xmlreader.GetValueAsString("mytv", "h264videocodec", ""); } //Find the type of decoder required for the output video & audio pins on TSReader. Log.Info("TSReader2WMV: find tsreader compatible audio/video decoders"); IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("TSReader2WMV: FAILED: unable to get output pins of tsreader"); Cleanup(); return(false); } bool usingAAC = false; IEnumMediaTypes enumMediaTypes; hr = pinOut0.EnumMediaTypes(out enumMediaTypes); while (true) { AMMediaType[] mediaTypes = new AMMediaType[1]; int typesFetched; hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched); if (hr != 0 || typesFetched == 0) { break; } if (mediaTypes[0].majorType == MediaType.Audio && mediaTypes[0].subType == MediaSubType.LATMAAC) { Log.Info("TSReader2WMV: found LATM AAC audio out pin on tsreader"); usingAAC = true; } } bool usingH264 = false; hr = pinOut1.EnumMediaTypes(out enumMediaTypes); while (true) { AMMediaType[] mediaTypes = new AMMediaType[1]; int typesFetched; hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched); if (hr != 0 || typesFetched == 0) { break; } if (mediaTypes[0].majorType == MediaType.Video && mediaTypes[0].subType == AVC1) { Log.Info("TSReader2WMV: found H.264 video out pin on tsreader"); usingH264 = true; } } //Add the type of decoder required for the output video & audio pins on TSReader. Log.Info("TSReader2WMV: add audio/video decoders to graph"); if (usingH264 == false) { Log.Info("TSReader2WMV: add mpeg2 video decoder:{0}", strVideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); if (VideoCodec == null) { Log.Error("TSReader2WMV: unable to add mpeg2 video decoder"); Cleanup(); return(false); } } else { Log.Info("TSReader2WMV: add h264 video codec:{0}", strH264VideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec); if (VideoCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add h264 video codec"); Cleanup(); return(false); } } if (usingAAC == false) { Log.Info("TSReader2WMV: add mpeg2 audio codec:{0}", strAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add mpeg2 audio codec"); Cleanup(); return(false); } } else { Log.Info("TSReader2WMV: add aac audio codec:{0}", strAACAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add aac audio codec"); Cleanup(); return(false); } } Log.Info("TSReader2WMV: connect tsreader->audio/video decoders"); //connect output #0 (audio) of tsreader->audio decoder input pin 0 //connect output #1 (video) of tsreader->video decoder input pin 0 pinIn0 = DsFindPin.ByDirection(AudioCodec, PinDirection.Input, 0); //audio pinIn1 = DsFindPin.ByDirection(VideoCodec, PinDirection.Input, 0); //video if (pinIn0 == null || pinIn1 == null) { Log.Error("TSReader2WMV: FAILED: unable to get pins of video/audio codecs"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut0, pinIn0); if (hr != 0) { Log.Error("TSReader2WMV: FAILED: unable to connect audio pins :0x{0:X}", hr); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut1, pinIn1); if (hr != 0) { Log.Error("TSReader2WMV: FAILED: unable to connect video pins :0x{0:X}", hr); Cleanup(); return(false); } string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv"); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("TSReader2WMV: start pre-run"); mediaControl = graphBuilder as IMediaControl; mediaSeeking = tsreaderSource as IMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("TSReader2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration)); hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2WMV: FAILED: unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) { break; } maxCount--; if (maxCount <= 0) { break; } } Log.Info("TSReader2WMV: pre-run done"); Log.Info("TSReader2WMV: Get duration of movie"); mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); Log.Info("TSReader2WMV: reconnect mpeg2 video codec->ASF WM Writer"); graphBuilder.RemoveFilter(fileWriterbase); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("TSReader2WMV: Start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } } catch (Exception e) { // TODO: Handle exceptions. Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message); return(false); } return(true); }
public double CurrentPosition() { m_objMediaPosition = m_objFilterGraph as IMediaPosition; return(m_objMediaPosition.CurrentPosition); }
/// <summary> create the used COM components and get the interfaces. </summary> protected bool GetInterfaces() { VMR9Util.g_vmr9 = null; if (IsRadio == false) { Vmr9 = VMR9Util.g_vmr9 = new VMR9Util(); // switch back to directx fullscreen mode Log.Info("RTSPPlayer: Enabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 1, 0, null); GUIWindowManager.SendMessage(msg); } //Type comtype = null; //object comobj = null; DsRect rect = new DsRect(); rect.top = 0; rect.bottom = GUIGraphicsContext.form.Height; rect.left = 0; rect.right = GUIGraphicsContext.form.Width; try { graphBuilder = (IGraphBuilder)new FilterGraph(); Log.Info("RTSPPlayer: add source filter"); if (IsRadio == false) { bool AddVMR9 = VMR9Util.g_vmr9 != null && VMR9Util.g_vmr9.AddVMR9(graphBuilder); if (!AddVMR9) { Log.Error("RTSPPlayer:Failed to add VMR9 to graph"); return false; } VMR9Util.g_vmr9.Enable(false); } _mpegDemux = (IBaseFilter)new MPEG2Demultiplexer(); graphBuilder.AddFilter(_mpegDemux, "MPEG-2 Demultiplexer"); _rtspSource = (IBaseFilter)new RtpSourceFilter(); int hr = graphBuilder.AddFilter((IBaseFilter)_rtspSource, "RTSP Source Filter"); if (hr != 0) { Log.Error("RTSPPlayer:unable to add RTSP source filter:{0:X}", hr); return false; } // add preferred video & audio codecs Log.Info("RTSPPlayer: add video/audio codecs"); string strVideoCodec = ""; string strAudioCodec = ""; string strAudiorenderer = ""; int intFilters = 0; // FlipGer: count custom filters string strFilters = ""; // FlipGer: collect custom filters string postProcessingFilterSection = "mytv"; using (Settings xmlreader = new MPSettings()) { if (_mediaType == g_Player.MediaType.Video) { strVideoCodec = xmlreader.GetValueAsString("movieplayer", "mpeg2videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("movieplayer", "mpeg2audiocodec", ""); strAudiorenderer = xmlreader.GetValueAsString("movieplayer", "audiorenderer", "Default DirectSound Device"); postProcessingFilterSection = "movieplayer"; } else { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", ""); strAudiorenderer = xmlreader.GetValueAsString("mytv", "audiorenderer", "Default DirectSound Device"); postProcessingFilterSection = "mytv"; } enableDvbSubtitles = xmlreader.GetValueAsBool("tvservice", "dvbsubtitles", false); // FlipGer: load infos for custom filters int intCount = 0; while (xmlreader.GetValueAsString(postProcessingFilterSection, "filter" + intCount.ToString(), "undefined") != "undefined") { if (xmlreader.GetValueAsBool(postProcessingFilterSection, "usefilter" + intCount.ToString(), false)) { strFilters += xmlreader.GetValueAsString(postProcessingFilterSection, "filter" + intCount.ToString(), "undefined") + ";"; intFilters++; } intCount++; } } string extension = Path.GetExtension(m_strCurrentFile).ToLowerInvariant(); if (IsRadio == false) { if (strVideoCodec.Length > 0) { DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); } } if (strAudioCodec.Length > 0) { DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); } if (enableDvbSubtitles == true) { try { _subtitleFilter = SubtitleRenderer.GetInstance().AddSubtitleFilter(graphBuilder); SubtitleRenderer.GetInstance().SetPlayer(this); dvbSubRenderer = SubtitleRenderer.GetInstance(); } catch (Exception e) { Log.Error(e); } } Log.Debug("Is subtitle fitler null? {0}", (_subtitleFilter == null)); // FlipGer: add custom filters to graph string[] arrFilters = strFilters.Split(';'); for (int i = 0; i < intFilters; i++) { DirectShowUtil.AddFilterToGraph(graphBuilder, arrFilters[i]); } if (strAudiorenderer.Length > 0) { audioRendererFilter = DirectShowUtil.AddAudioRendererToGraph(graphBuilder, strAudiorenderer, false); } Log.Info("RTSPPlayer: load:{0}", m_strCurrentFile); IFileSourceFilter interfaceFile = (IFileSourceFilter)_rtspSource; if (interfaceFile == null) { Log.Error("RTSPPlayer:Failed to get IFileSourceFilter"); return false; } //Log.Info("RTSPPlayer: open file:{0}",filename); hr = interfaceFile.Load(m_strCurrentFile, null); if (hr != 0) { Log.Error("RTSPPlayer:Failed to open file:{0} :0x{1:x}", m_strCurrentFile, hr); return false; } #region connect rtspsource->demux Log.Info("RTSPPlayer:connect rtspsource->mpeg2 demux"); IPin pinTsOut = DsFindPin.ByDirection((IBaseFilter)_rtspSource, PinDirection.Output, 0); if (pinTsOut == null) { Log.Info("RTSPPlayer:failed to find output pin of tsfilesource"); return false; } IPin pinDemuxIn = DsFindPin.ByDirection(_mpegDemux, PinDirection.Input, 0); if (pinDemuxIn == null) { Log.Info("RTSPPlayer:failed to find output pin of tsfilesource"); return false; } hr = graphBuilder.Connect(pinTsOut, pinDemuxIn); if (hr != 0) { Log.Info("RTSPPlayer:failed to connect rtspsource->mpeg2 demux:{0:X}", hr); return false; } DirectShowUtil.ReleaseComObject(pinTsOut); DirectShowUtil.ReleaseComObject(pinDemuxIn); #endregion #region render demux output pins if (IsRadio) { Log.Info("RTSPPlayer:render audio demux outputs"); IEnumPins enumPins; _mpegDemux.EnumPins(out enumPins); IPin[] pins = new IPin[2]; int fetched = 0; while (enumPins.Next(1, pins, out fetched) == 0) { if (fetched != 1) { break; } PinDirection direction; pins[0].QueryDirection(out direction); if (direction == PinDirection.Input) { continue; } IEnumMediaTypes enumMediaTypes; pins[0].EnumMediaTypes(out enumMediaTypes); AMMediaType[] mediaTypes = new AMMediaType[20]; int fetchedTypes; enumMediaTypes.Next(20, mediaTypes, out fetchedTypes); for (int i = 0; i < fetchedTypes; ++i) { if (mediaTypes[i].majorType == MediaType.Audio) { graphBuilder.Render(pins[0]); break; } } } } else { Log.Info("RTSPPlayer:render audio/video demux outputs"); IEnumPins enumPins; _mpegDemux.EnumPins(out enumPins); IPin[] pins = new IPin[2]; int fetched = 0; while (enumPins.Next(1, pins, out fetched) == 0) { if (fetched != 1) { break; } PinDirection direction; pins[0].QueryDirection(out direction); if (direction == PinDirection.Input) { continue; } graphBuilder.Render(pins[0]); } } #endregion // Connect DVB subtitle filter pins in the graph if (_mpegDemux != null && enableDvbSubtitles == true) { IMpeg2Demultiplexer demuxer = _mpegDemux as IMpeg2Demultiplexer; hr = demuxer.CreateOutputPin(GetTSMedia(), "Pcr", out _pinPcr); if (hr == 0) { Log.Info("RTSPPlayer:_pinPcr OK"); IPin pDemuxerPcr = DsFindPin.ByName(_mpegDemux, "Pcr"); IPin pSubtitlePcr = DsFindPin.ByName(_subtitleFilter, "Pcr"); hr = graphBuilder.Connect(pDemuxerPcr, pSubtitlePcr); } else { Log.Info("RTSPPlayer:Failed to create _pinPcr in demuxer:{0:X}", hr); } hr = demuxer.CreateOutputPin(GetTSMedia(), "Subtitle", out _pinSubtitle); if (hr == 0) { Log.Info("RTSPPlayer:_pinSubtitle OK"); IPin pDemuxerSubtitle = DsFindPin.ByName(_mpegDemux, "Subtitle"); IPin pSubtitle = DsFindPin.ByName(_subtitleFilter, "In"); hr = graphBuilder.Connect(pDemuxerSubtitle, pSubtitle); } else { Log.Info("RTSPPlayer:Failed to create _pinSubtitle in demuxer:{0:X}", hr); } hr = demuxer.CreateOutputPin(GetTSMedia(), "PMT", out _pinPMT); if (hr == 0) { Log.Info("RTSPPlayer:_pinPMT OK"); IPin pDemuxerSubtitle = DsFindPin.ByName(_mpegDemux, "PMT"); IPin pSubtitle = DsFindPin.ByName(_subtitleFilter, "PMT"); hr = graphBuilder.Connect(pDemuxerSubtitle, pSubtitle); } else { Log.Info("RTSPPlayer:Failed to create _pinPMT in demuxer:{0:X}", hr); } } if (IsRadio == false) { if (!VMR9Util.g_vmr9.IsVMR9Connected) { //VMR9 is not supported, switch to overlay Log.Info("RTSPPlayer: vmr9 not connected"); _mediaCtrl = null; Cleanup(); return false; } VMR9Util.g_vmr9.SetDeinterlaceMode(); } _mediaCtrl = (IMediaControl)graphBuilder; mediaEvt = (IMediaEventEx)graphBuilder; _mediaSeeking = (IMediaSeeking)graphBuilder; mediaPos = (IMediaPosition)graphBuilder; basicAudio = graphBuilder as IBasicAudio; //DirectShowUtil.SetARMode(graphBuilder,AspectRatioMode.Stretched); DirectShowUtil.EnableDeInterlace(graphBuilder); if (VMR9Util.g_vmr9 != null) { m_iVideoWidth = VMR9Util.g_vmr9.VideoWidth; m_iVideoHeight = VMR9Util.g_vmr9.VideoHeight; } if (audioRendererFilter != null) { Log.Info("RTSPPlayer9:set reference clock"); IMediaFilter mp = graphBuilder as IMediaFilter; IReferenceClock clock = audioRendererFilter as IReferenceClock; hr = mp.SetSyncSource(null); hr = mp.SetSyncSource(clock); Log.Info("RTSPPlayer9:set reference clock:{0:X}", hr); } Log.Info("RTSPPlayer: graph build successfull"); return true; } catch (Exception ex) { Error.SetError("Unable to play movie", "Unable build graph for VMR9"); Log.Error("RTSPPlayer:exception while creating DShow graph {0} {1}", ex.Message, ex.StackTrace); CloseInterfaces(); return false; } }
public double Duration() { m_objMediaPosition = m_objFilterGraph as IMediaPosition; return(m_objMediaPosition.Duration); }
private void StartCapture() { int hr; ISampleGrabber sampGrabber = null; IBaseFilter capFilter = null; ICaptureGraphBuilder2 capGraph = null; if (System.IO.File.Exists(txtAviFileName.Text)) { // Get the graphbuilder object m_FilterGraph = (IFilterGraph2) new FilterGraph(); m_mediaCtrl = m_FilterGraph as IMediaControl; // Get the ICaptureGraphBuilder2 capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); // Get the SampleGrabber interface sampGrabber = (ISampleGrabber) new SampleGrabber(); // Start building the graph hr = capGraph.SetFiltergraph(m_FilterGraph); DsError.ThrowExceptionForHR(hr); // Add the video source hr = m_FilterGraph.AddSourceFilter(txtAviFileName.Text, "File Source (Async.)", out capFilter); DsError.ThrowExceptionForHR(hr); //add AVI Decompressor IBaseFilter pAVIDecompressor = (IBaseFilter) new AVIDec(); hr = m_FilterGraph.AddFilter(pAVIDecompressor, "AVI Decompressor"); DsError.ThrowExceptionForHR(hr); // IBaseFilter baseGrabFlt = (IBaseFilter)sampGrabber; ConfigureSampleGrabber(sampGrabber); // Add the frame grabber to the graph hr = m_FilterGraph.AddFilter(baseGrabFlt, "Ds.NET Grabber"); DsError.ThrowExceptionForHR(hr); IBaseFilter vidrender = (IBaseFilter) new VideoRenderer(); hr = m_FilterGraph.AddFilter(vidrender, "Render"); DsError.ThrowExceptionForHR(hr); IPin captpin = DsFindPin.ByDirection(capFilter, PinDirection.Output, 0); IPin samppin = DsFindPin.ByName(baseGrabFlt, "Input"); hr = m_FilterGraph.Connect(captpin, samppin); DsError.ThrowExceptionForHR(hr); FileWriter filewritter = new FileWriter(); IFileSinkFilter filemux = (IFileSinkFilter)filewritter; //filemux.SetFileName("test.avi",); //hr = capGraph.RenderStream(null, MediaType.Video, capFilter, null, vidrender); // DsError.ThrowExceptionForHR(hr); SaveSizeInfo(sampGrabber); // setup buffer if (m_handle == IntPtr.Zero) { m_handle = Marshal.AllocCoTaskMem(m_stride * m_videoHeight); } // tell the callback to ignore new images m_PictureReady = new ManualResetEvent(false); m_bGotOne = false; m_bRunning = false; timer1 = new Thread(timer); timer1.IsBackground = true; timer1.Start(); m_mediaextseek = m_FilterGraph as IAMExtendedSeeking; m_mediapos = m_FilterGraph as IMediaPosition; m_mediaseek = m_FilterGraph as IMediaSeeking; double length = 0; m_mediapos.get_Duration(out length); trackBar_mediapos.Minimum = 0; trackBar_mediapos.Maximum = (int)length; Start(); } else { MessageBox.Show("File does not exist"); } }
// Build the capture graph for grabber and renderer.</summary> // (Control to show video in, Filename to play) private void SetupGraph(Control hWin, string FileName) { int hr; // Get the graphbuilder object m_graphBuilder = new FilterGraph() as IFilterGraph2; // Get a ICaptureGraphBuilder2 to help build the graph ICaptureGraphBuilder2 icgb2 = new CaptureGraphBuilder2() as ICaptureGraphBuilder2; try { // Link the ICaptureGraphBuilder2 to the IFilterGraph2 hr = icgb2.SetFiltergraph(m_graphBuilder); DsError.ThrowExceptionForHR(hr); #if DEBUG // Allows you to view the graph with GraphEdit File/Connect m_DsRot = new DsROTEntry(m_graphBuilder); #endif // Add the filters necessary to render the file. This function will // work with a number of different file types. IBaseFilter sourceFilter = null; hr = m_graphBuilder.AddSourceFilter(FileName, FileName, out sourceFilter); DsError.ThrowExceptionForHR(hr); // Get the SampleGrabber interface m_sampGrabber = (ISampleGrabber) new SampleGrabber(); IBaseFilter baseGrabFlt = (IBaseFilter)m_sampGrabber; // Configure the Sample Grabber ConfigureSampleGrabber(m_sampGrabber); // Add it to the filter hr = m_graphBuilder.AddFilter(baseGrabFlt, "Ds.NET Grabber"); DsError.ThrowExceptionForHR(hr); // Connect the pieces together, use the default renderer hr = icgb2.RenderStream(null, null, sourceFilter, baseGrabFlt, null); DsError.ThrowExceptionForHR(hr); // Now that the graph is built, read the dimensions of the bitmaps we'll be getting SaveSizeInfo(m_sampGrabber); // Configure the Video Window IVideoWindow videoWindow = m_graphBuilder as IVideoWindow; ConfigureVideoWindow(videoWindow, hWin); // Grab some other interfaces m_mediaEvent = m_graphBuilder as IMediaEvent; m_mediaCtrl = m_graphBuilder as IMediaControl; m_mediaPosition = m_graphBuilder as IMediaPosition; m_mediaSeeking = m_graphBuilder as IMediaSeeking; } finally { if (icgb2 != null) { Marshal.ReleaseComObject(icgb2); icgb2 = null; } } #if DEBUG // Double check to make sure we aren't releasing something // important. GC.Collect(); GC.WaitForPendingFinalizers(); #endif }
/// <summary> /// Closes DirectShow interfaces /// </summary> private void CloseInterfaces() { if (m_mediaEvent != null) { m_mediaControl.Stop(); //0x00008001 = WM_GRAPHNOTIFY m_mediaEvent.SetNotifyWindow(IntPtr.Zero, 0x00008001, IntPtr.Zero); } m_mediaControl = null; m_mediaEvent = null; m_graphBuilder = null; m_mediaSeeking = null; m_mediaPosition = null; m_basicAudio = null; if (m_comObject != null) Marshal.ReleaseComObject(m_comObject); m_comObject = null; }
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; //this.basicAudio = this.graphBuilder as AudioRender; // 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; }
// // Starts playback for the selected stream at the specified time // int OpenStream(string videopath, double videotime) { double td; // store stream duration; int hr = 0; // animate bt logo // logo_webbrowser.Refresh(); // cover overlay options with video or not // if overlay is active ////////if (OverlayButton.Checked) // Overlay button config - Melek ////////{ //////// VideoPanel.Width = VideoPlayerPanel.Width - OverlayPanel.Width; //////// OverlayBar.Location = new System.Drawing.Point(-1, -1); ; //////// OverlayBar.Text = ">"; ////////} ////////else ////////// if overlay is not active ////////{ //////// VideoPanel.Width = VideoPlayerPanel.Width - OverlayBar.Width; //////// OverlayBar.Location = new System.Drawing.Point(OverlayPanel.Width - OverlayBar.Width - 1, -1); ; //////// OverlayBar.Text = "<"; ////////} filename = videopath; try//Melek { if (filename == string.Empty) return -1; // this.graphBuilder = (IGraphBuilder)new FilterGraph(); this.graphBuilder = (IFilterGraph2)new FilterGraph(); // We manually add the VMR (video mixer/renderer) filter so that we can set it into "mixing" mode. // That is needed so that the VMR will deinterlace before playing back VideoMixingRenderer vmr = new VideoMixingRenderer(); //Tom's deinterlace changes graphBuilder.AddFilter((IBaseFilter)vmr, "vmr");//Tom's deinterlace changes IVMRFilterConfig vmrConfig = vmr as IVMRFilterConfig;//Tom's deinterlace changes int nRet = vmrConfig.SetNumberOfStreams(1);//Tom's deinterlace changes // BuildVideoGraph(videopath); //No more overlay - Melek hr = this.graphBuilder.RenderFile(filename, null);//MELek - instead of calling BuildVideoGraph function call RenderFile function directly DsError.ThrowExceptionForHR(hr);//Melek // 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.VideoPanel.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 // hr = InitPlayerWindow(); // DsError.ThrowExceptionForHR(hr); //EnablePlaybackMenu(true, MediaType.Audio); //} // Complete window initialization //CheckSizeMenu(menuFileSizeNormal); //this.isFullScreen = false; this.currentPlaybackRate = 1.0; #if DEBUG rot = new DsROTEntry(this.graphBuilder); #endif // check the mute button MuteStatus(); // Run the graph to play the media file this.mediaPosition.put_CurrentPosition(videotime); hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); this.currentState = PlayState.Running; UpdateMainTitle(); try { #if !DEMO this.mediaPosition.get_Duration(out td); #else td=vs.getDurationInSeconds(); #endif this.VideoProgressionBar.Minimum = 0; this.VideoProgressionBar.Maximum = (int)(td * 100); isTimer = true; // disable if raw 264 files are open (.264 or .h264) as they dont allow seeking if (videopath.EndsWith("264")) this.mediaSeeking = null; return 0; } catch (Exception ex) { //Global.log("Problem opening " + vs.path.Name + ".ts\n" + ex); Global.log("Problem opening " + vs.StreamFileName + "\n" + ex); //Melek - path.name => streamfilename EnablePlayback(false); //MElek return -1; } } catch (Exception ex) //Melek { // MessageBox.Show(ex.Message); EnablePlayback(false); return -1; } }
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 StopAnimation() { if (isPlaying) { master.Stop(); if (master.form != null) { master.form.Invoke((MethodInvoker)delegate() { master.form.M_PrevSize.Enabled = true; }); } media.Stop(); if (eventEx != null) { eventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); eventEx = null; } if (window != null) { window.put_Visible(OABool.False); window.put_Owner(IntPtr.Zero); window = null; } iba = null; imp = null; igb = null; render = null; media = null; graph = null; master.Stop(); isPlaying = false; } }
public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard) { try { if (!Supports(format)) { return(false); } string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLowerInvariant() != ".dvr-ms" && ext.ToLowerInvariant() != ".sbe") { Log.Info("DVRMS2WMV: wrong file format"); return(false); } Log.Info("DVRMS2WMV: create graph"); graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("DVRMS2WMV: add streambuffersource"); bufferSource = (IStreamBufferSource) new StreamBufferSource(); IBaseFilter filter = (IBaseFilter)bufferSource; graphBuilder.AddFilter(filter, "SBE SOURCE"); Log.Info("DVRMS2WMV: load file:{0}", info.file); IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource; int hr = fileSource.Load(info.file, null); //add mpeg2 audio/video codecs string strVideoCodec = ""; string strAudioCodec = ""; using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings()) { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", "MPC - MPEG-2 Video Decoder (Gabest)"); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", "MPC - MPA Decoder Filter"); } Log.Info("DVRMS2WMV: add mpeg2 video codec:{0}", strVideoCodec); Mpeg2VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:Add mpeg2 video to filtergraph :0x{0:X}", hr); Cleanup(); return(false); } Log.Info("DVRMS2WMV: add mpeg2 audio codec:{0}", strAudioCodec); Mpeg2AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (Mpeg2AudioCodec == null) { Log.Error("DVRMS2WMV:FAILED:unable to add mpeg2 audio codec"); Cleanup(); return(false); } Log.Info("DVRMS2WMV: connect streambufer source->mpeg audio/video decoders"); //connect output #0 of streambuffer source->mpeg2 audio codec pin 1 //connect output #1 of streambuffer source->mpeg2 video codec pin 1 IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get pins of source"); Cleanup(); return(false); } pinIn0 = DsFindPin.ByDirection(Mpeg2VideoCodec, PinDirection.Input, 0); //video pinIn1 = DsFindPin.ByDirection(Mpeg2AudioCodec, PinDirection.Input, 0); //audio if (pinIn0 == null || pinIn1 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get pins of mpeg2 video/audio codec"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut0, pinIn1); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to connect audio pins :0x{0:X}", hr); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut1, pinIn0); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to connect video pins :0x{0:X}", hr); Cleanup(); return(false); } string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv"); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("DVRMS2WMV: start pre-run"); mediaControl = graphBuilder as IMediaControl; mediaSeeking = bufferSource as IStreamBufferMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("DVRMS2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration)); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) { break; } maxCount--; if (maxCount <= 0) { break; } } Log.Info("DVRMS2WMV: pre-run done"); Log.Info("DVRMS2WMV: Get duration of movie"); mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); Log.Info("DVRMS2WMV: reconnect mpeg2 video codec->ASF WM Writer"); graphBuilder.RemoveFilter(fileWriterbase); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("DVRMS2WMV: Start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } } catch (Exception e) { // TODO: Handle exceptions. Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message); return(false); } return(true); }
private void CleanUp() { if (m_objMediaControl != null) { m_objMediaControl.Stop(); } m_CurrentStatus = MediaStatus.Stopped; 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; } }
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() { if (graphBuilder == null) { return; } int hr; Log.Info("RTSPPlayer:cleanup DShow graph"); try { 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("RTSPPlayer: graph still running"); if (GUIGraphicsContext.InVmr9Render) Log.Error("RTSPPlayer: 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; 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.ReleaseComObject(graphBuilder); graphBuilder = null; } if (Vmr9 != null) { Vmr9.SafeDispose(); Vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; if (_mpegDemux != null) { Log.Info("cleanup mpegdemux"); while ((hr = DirectShowUtil.ReleaseComObject(_mpegDemux)) > 0) { ; } _mpegDemux = null; } if (_rtspSource != null) { Log.Info("cleanup _rtspSource"); while ((hr = DirectShowUtil.ReleaseComObject(_rtspSource)) > 0) { ; } _rtspSource = null; } if (_subtitleFilter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_subtitleFilter)) > 0) { ; } _subtitleFilter = null; if (this.dvbSubRenderer != null) { this.dvbSubRenderer.SetPlayer(null); } this.dvbSubRenderer = null; } if (vobSub != null) { Log.Info("cleanup vobSub"); while ((hr = DirectShowUtil.ReleaseComObject(vobSub)) > 0) { ; } 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); }
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; }
/// <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); } }
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 BuildGraph() { int hr; try { lblTotalTime.Text = mvs.PlayTime.ToString(); TimeSpan tt = TimeSpan.Parse(mvs.PlayTime); DateTime dt = new DateTime(tt.Ticks); lblTotalTime.Text = String.Format("{0:HH:mm:ss}", dt); if (mvs.LocalMedia[0].IsDVD) { mediaToPlay = mvs.LocalMedia[0]; MediaState mediaState = mediaToPlay.State; if (mediaState == MediaState.NotMounted) { MountResult result = mediaToPlay.Mount(); } string videoPath = mediaToPlay.GetVideoPath(); if (videoPath != null) FirstPlayDvd(videoPath); else FirstPlayDvd(mvs.LocalMedia[0].File.FullName); // Add delegates for Windowless operations AddHandlers(); MainForm_ResizeMove(null, null); } else { _graphBuilder = (IFilterGraph2)new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)_graphBuilder); _mediaCtrl = (IMediaControl)_graphBuilder; _mediaSeek = (IMediaSeeking)_graphBuilder; _mediaPos = (IMediaPosition)_graphBuilder; _mediaStep = (IVideoFrameStep)_graphBuilder; _vmr9Filter = (IBaseFilter)new VideoMixingRenderer9(); ConfigureVMR9InWindowlessMode(); AddHandlers(); MainForm_ResizeMove(null, null); hr = _graphBuilder.AddFilter(_vmr9Filter, "Video Mixing Render 9"); AddPreferedCodecs(_graphBuilder); DsError.ThrowExceptionForHR(hr); hr = _graphBuilder.RenderFile(mvs.LocalMedia[0].File.FullName, null); DsError.ThrowExceptionForHR(hr); } } catch (Exception e) { CloseDVDInterfaces(); logger.ErrorException("An error occured during the graph building : \r\n\r\n",e); } }
private void Cleanup() { if (graphBuilder == null) { return; } int hr; Log.Info("RTSPPlayer:cleanup DShow graph"); try { 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("RTSPPlayer: graph still running"); } if (GUIGraphicsContext.InVmr9Render) { Log.Error("RTSPPlayer: 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; 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.ReleaseComObject(graphBuilder); graphBuilder = null; } if (Vmr9 != null) { Vmr9.SafeDispose(); Vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; if (_mpegDemux != null) { Log.Info("cleanup mpegdemux"); while ((hr = DirectShowUtil.ReleaseComObject(_mpegDemux)) > 0) { ; } _mpegDemux = null; } if (_rtspSource != null) { Log.Info("cleanup _rtspSource"); while ((hr = DirectShowUtil.ReleaseComObject(_rtspSource)) > 0) { ; } _rtspSource = null; } if (_subtitleFilter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_subtitleFilter)) > 0) { ; } _subtitleFilter = null; if (this.dvbSubRenderer != null) { this.dvbSubRenderer.SetPlayer(null); } this.dvbSubRenderer = null; } if (vobSub != null) { Log.Info("cleanup vobSub"); while ((hr = DirectShowUtil.ReleaseComObject(vobSub)) > 0) { ; } 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 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); }
public void CloseFile() { int hr = 0; // Stop media playback if (this.mediaControl != null) { hr = this.mediaControl.Stop(); } // Free DirectShow interfaces try { lock (this) { // Relinquish ownership after hiding video window if (this.MediaType == MediaType.AudioVideo) { 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); } // 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 { } // Reset properties this.MediaFile = null; this.MediaType = MediaType.Unknown; this.Length = null; this.Resolution = null; this.PlaybackStatus = PlayState.Closed; }
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); } }
/// <summary> /// Closes DirectShow interfaces /// </summary> private void CloseInterfaces() { if (me != null) { DsError.ThrowExceptionForHR(mc.Stop()); //0x00008001 = WM_GRAPHNOTIFY DsError.ThrowExceptionForHR(me.SetNotifyWindow(IntPtr.Zero, 0x00008001, IntPtr.Zero)); } mc = null; me = null; gb = null; ms = null; mp = null; if (fg != null) Marshal.ReleaseComObject(fg); fg = null; }
private void StartCapture() { int hr; ISampleGrabber sampGrabber = null; IBaseFilter capFilter = null; ICaptureGraphBuilder2 capGraph = null; if (System.IO.File.Exists(txtAviFileName.Text)) { // Get the graphbuilder object m_FilterGraph = (IFilterGraph2) new FilterGraph(); m_mediaCtrl = m_FilterGraph as IMediaControl; // Get the ICaptureGraphBuilder2 capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); // Get the SampleGrabber interface sampGrabber = (ISampleGrabber) new SampleGrabber(); // Start building the graph hr = capGraph.SetFiltergraph(m_FilterGraph); DsError.ThrowExceptionForHR(hr); // Add the video source hr = m_FilterGraph.AddSourceFilter(txtAviFileName.Text, "File Source (Async.)", out capFilter); DsError.ThrowExceptionForHR(hr); //add AVI Decompressor IBaseFilter pAVIDecompressor = (IBaseFilter) new AVIDec(); hr = m_FilterGraph.AddFilter(pAVIDecompressor, "AVI Decompressor"); DsError.ThrowExceptionForHR(hr); IBaseFilter ffdshow; try { // Create Decoder filter COM object (ffdshow video decoder) Type comtype = Type.GetTypeFromCLSID(new Guid("{04FE9017-F873-410E-871E-AB91661A4EF7}")); if (comtype == null) throw new NotSupportedException("Creating ffdshow video decoder COM object fails."); object comobj = Activator.CreateInstance(comtype); ffdshow = (IBaseFilter) comobj; // error ocurrs! raised exception comobj = null; } catch { CustomMessageBox.Show("Please install/reinstall ffdshow"); return; } hr = m_FilterGraph.AddFilter(ffdshow, "ffdshow"); DsError.ThrowExceptionForHR(hr); // IBaseFilter baseGrabFlt = (IBaseFilter) sampGrabber; ConfigureSampleGrabber(sampGrabber); // Add the frame grabber to the graph hr = m_FilterGraph.AddFilter(baseGrabFlt, "Ds.NET Grabber"); DsError.ThrowExceptionForHR(hr); IBaseFilter vidrender = (IBaseFilter) new VideoRenderer(); hr = m_FilterGraph.AddFilter(vidrender, "Render"); DsError.ThrowExceptionForHR(hr); IPin captpin = DsFindPin.ByDirection(capFilter, PinDirection.Output, 0); IPin ffdpinin = DsFindPin.ByName(ffdshow, "In"); IPin ffdpinout = DsFindPin.ByName(ffdshow, "Out"); IPin samppin = DsFindPin.ByName(baseGrabFlt, "Input"); hr = m_FilterGraph.Connect(captpin, ffdpinin); DsError.ThrowExceptionForHR(hr); hr = m_FilterGraph.Connect(ffdpinout, samppin); DsError.ThrowExceptionForHR(hr); FileWriter filewritter = new FileWriter(); IFileSinkFilter filemux = (IFileSinkFilter) filewritter; //filemux.SetFileName("test.avi",); //hr = capGraph.RenderStream(null, MediaType.Video, capFilter, null, vidrender); // DsError.ThrowExceptionForHR(hr); SaveSizeInfo(sampGrabber); // setup buffer if (m_handle == IntPtr.Zero) m_handle = Marshal.AllocCoTaskMem(m_stride*m_videoHeight); // tell the callback to ignore new images m_PictureReady = new ManualResetEvent(false); m_bGotOne = false; m_bRunning = false; timer1 = new Thread(timer); timer1.IsBackground = true; timer1.Start(); m_mediaextseek = m_FilterGraph as IAMExtendedSeeking; m_mediapos = m_FilterGraph as IMediaPosition; m_mediaseek = m_FilterGraph as IMediaSeeking; double length = 0; m_mediapos.get_Duration(out length); trackBar_mediapos.Minimum = 0; trackBar_mediapos.Maximum = (int) length; Start(); } else { MessageBox.Show("File does not exist"); } }
/// <summary> /// Initialises DirectShow interfaces /// </summary> private void InitInterfaces() { fg = new FilterGraph(); gb = (IGraphBuilder)fg; mc = (IMediaControl)fg; me = (IMediaEventEx)fg; ms = (IMediaSeeking)fg; mp = (IMediaPosition)fg; }
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> do cleanup and release DirectShow. </summary> private void CloseInterfaces() { if (graphBuilder == null) { return; } Logger.Instance.Debug("AirplayerAudioPlayer: Close interfaces"); int hr; try { if (mediaCtrl != null) { int counter = 0; FilterState state; hr = mediaCtrl.Stop(); hr = mediaCtrl.GetState(10, out state); while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render) { System.Threading.Thread.Sleep(100); hr = mediaCtrl.GetState(10, out state); counter++; if (counter >= 30) { if (state != FilterState.Stopped) { Logger.Instance.Debug("ShairportPlayer: graph still running"); } if (GUIGraphicsContext.InVmr9Render) { Logger.Instance.Debug("ShairportPlayer: in renderer"); } break; } } mediaCtrl = null; } m_state = PlayState.Init; if (mediaEvt != null) { hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); mediaEvt = null; } mediaSeek = null; mediaPos = null; basicAudio = null; if (graphBuilder != null) { if (_rotEntry != null) { _rotEntry.Dispose(); _rotEntry = null; } Marshal.ReleaseComObject(graphBuilder); graphBuilder = null; } m_state = PlayState.Init; Logger.Instance.Debug("AirplayerAudioPlayer: Interfaces closed"); } catch (Exception ex) { Logger.Instance.Debug("AirplayerAudioPlayer: Exception closing interfaces '{0}'\r\n{1}", ex.Message, ex.StackTrace); } }