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); } }
public int SetPosition(long tStart) { IMediaSeeking pSeek = m_pGraph as IMediaSeeking; int hr = E_NOINTERFACE; if (pSeek != null) { // input time is relative to clip start -- add on offset // from start of media tStart += m_tStart; if (m_tStop == 0) { hr = pSeek.SetPositions( tStart, AMSeekingSeekingFlags.AbsolutePositioning, null, AMSeekingSeekingFlags.NoPositioning); } else { hr = pSeek.SetPositions( tStart, AMSeekingSeekingFlags.AbsolutePositioning, m_tStop, AMSeekingSeekingFlags.AbsolutePositioning); } } return(hr); }
/// <summary> /// Creates a new IFilterGraph2 interface. /// </summary> protected virtual void CreateGraphBuilder() { _graphBuilder = (IFilterGraph2) new FilterGraph(); _mc = (IMediaControl)_graphBuilder; _me = (IMediaEventEx)_graphBuilder; _ms = (IMediaSeeking)_graphBuilder; }
public void Play(Resource resource) { // Have the graph builder construct its the appropriate graph automatically if (this.currentMediaFile.Equals(resource.FullName)) { return; } this.graphBuilder = (IGraphBuilder) new FilterGraph(); hr = this.graphBuilder.RenderFile(resource.FullName, null); DsError.ThrowExceptionForHR(hr); // QueryInterface for DirectShow interfaces this.mediaControl = (IMediaControl)this.graphBuilder; this.mediaEventEx = (IMediaEventEx)this.graphBuilder; this.mediaSeeking = (IMediaSeeking)this.graphBuilder; this.mediaPosition = (IMediaPosition)this.graphBuilder; // Query for video interfaces, which may not be relevant for audio files this.videoWindow = this.graphBuilder as IVideoWindow; this.basicVideo = this.graphBuilder as IBasicVideo; // Query for audio interfaces, which may not be relevant for video-only files this.basicAudio = this.graphBuilder as IBasicAudio; this.MoveVideoWindow(); this.mediaControl.Run(); this.currentMediaFile = resource.FullName; }
private void DoSetRate(double newRate) { int hr; IMediaControl mc = (IMediaControl)currentFilterGraph; // Stop hr = mc.Stop(); DsError.ThrowExceptionForHR(hr); // Stop ASFWriter hr = currentOutputFilter.Stop(); DsError.ThrowExceptionForHR(hr); if (UsingSBEFilter) { IStreamBufferMediaSeeking mSeek = (IStreamBufferMediaSeeking)currentSBEfilter; DsLong lDouble = DsLong.FromInt64(Convert.ToInt64(newRate)); hr = mSeek.SetRate(lDouble); DsError.ThrowExceptionForHR(hr); } else { // IMediaSeeking is used on the filter graph which distributes the calls IMediaSeeking mSeek = (IMediaSeeking)currentFilterGraph; hr = mSeek.SetRate(newRate); DsError.ThrowExceptionForHR(hr); } // Start ASF hr = currentOutputFilter.Run(0); DsError.ThrowExceptionForHR(hr); // Run again hr = mc.Run(); DsError.ThrowExceptionForHR(hr); }
/// <summary> do cleanup and release DirectShow. </summary> private void CloseInterfaces() { 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) { Log.Debug("AudioPlayerVMR: graph still running"); } if (GUIGraphicsContext.InVmr9Render) { Log.Debug("AudioPlayerVMR: 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.SafeDispose(); _rotEntry = null; } DirectShowUtil.ReleaseComObject(graphBuilder); graphBuilder = null; } m_state = PlayState.Init; } catch (Exception) {} }
/// <summary> /// Called when a node or a connection is added/removed in the DaggerLib graph /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Graph_OnTopologyChanged(object sender, EventArgs e) { // the topology of the graph has changed // see if seeking is available and set the extent of the TimeSliderControl _mediaSeeking = _graph as IMediaSeeking; if (_mediaSeeking != null) { long duration = 0; _mediaSeeking.GetDuration(out duration); // only set the extents if something has changed if (_timeSliderControl.Extent != (int)(duration / 10000)) { _timeSliderControl.Extent = (int)(duration / 10000); _timeSliderControl.Min = 0; _timeSliderControl.Max = _timeSliderControl.Extent; } } // see if frame step is available _frameStepButton.Enabled = GetFrameStepInterface(); // see if IVideoWindow is available _videoWindow = _graph as IVideoWindow; }
public void DoTests() { m_graphBuilder = BuildGraph(g_TestFile); m_ims = m_graphBuilder as IMediaSeeking; try { TestCaps(); TestFormats(); TestRate(); TestPosition(); TestPreRoll(); TestSetPosition(); TestConvert(); } finally { if (m_graphBuilder != null) { Marshal.ReleaseComObject(m_graphBuilder); } m_graphBuilder = null; m_ims = null; } }
private void DestroyFilters() { isValid = false; if (mediaControl != null) { mediaControl.Stop(); } // release all objects graph = null; mediaControl = null; mediaEvent = null; mediaSeekControl = null; if (graphObject != null) { Marshal.ReleaseComObject(graphObject); graphObject = null; } if (sourceBase != null) { Marshal.ReleaseComObject(sourceBase); sourceBase = null; } if (grabberObjectAudio != null) { Marshal.ReleaseComObject(grabberObjectAudio); grabberObjectAudio = null; } if (nullRendererObjectAudio != null) { Marshal.ReleaseComObject(nullRendererObjectAudio); grabberObjectAudio = null; } }
// Shut down capture public void CloseInterfaces() { int hr; IsOnDeleting = true; lock (this) { if (m_State != GraphState.Exiting) { m_State = GraphState.Exiting; // Release the thread (if the thread was started) if (m_mre != null) { m_mre.Set(); } } if (m_mediaCtrl != null) { // Stop the graph hr = m_mediaCtrl.Stop(); m_mediaCtrl = null; } if (m_mediaSeeking != null) { Marshal.ReleaseComObject(m_mediaSeeking); m_mediaSeeking = null; } if (m_sampGrabber != null) { Marshal.ReleaseComObject(m_sampGrabber); m_sampGrabber = null; } #if DEBUG if (m_DsRot != null) { m_DsRot.Dispose(); } #endif if (m_FilterGraph != null) { try { Marshal.ReleaseComObject(m_FilterGraph); } catch { } finally { m_FilterGraph = null; } } } GC.Collect(); }
public virtual bool SetPlaybackRate(double value) { if (_graphBuilder == null) { return(false); } IMediaSeeking mediaSeeking = _graphBuilder as IMediaSeeking; if (mediaSeeking == null) { return(false); } double currentRate; if (mediaSeeking.GetRate(out currentRate) == 0 && currentRate != value) { bool result = mediaSeeking.SetRate(value) == 0; if (result) { FirePlaybackStateChanged(); } return(result); } return(false); }
void FreeResources() { try { StopInternal(); StopGraphPollTimer(); _mediaSeeking = null; _mediaEvent = null; _mediaControl = null; if (_graph != null) { // Causes COMException GraphHelper.RemoveAllFilters(_graph); GraphHelper.SafeRelease(_graph); _graph = null; } } catch (InvalidComObjectException ex) { this.TraceDebug(ex.Message); } }
public PlayerCore(string file) { graphBuilder = (new FilterGraph()) as IFilterGraph2; if (graphBuilder == null) return; mediaControl = graphBuilder as IMediaControl; mediaSeeking = graphBuilder as IMediaSeeking; audioControl = graphBuilder as IBasicAudio; if (mediaControl == null || mediaSeeking == null || audioControl == null) return; //int hr = mediaControl.RenderFile(file); FileInfo info = new FileInfo(file); ISupport support = Supports.Instance[info.Extension]; int hr = -1; if (support != null) hr = support.RenderGraph(graphBuilder, file); else hr = mediaControl.RenderFile(file); fileName = file; if (hr != 0) errorStack.Push(hr); if (hr != 0) return; mediaSeeking.SetTimeFormat(TimeFormat.MediaTime); isValidate = true; window = graphBuilder as IVideoWindow; if (window != null) { int width = 0; int height = 0; window.get_Width(out width); window.get_Height(out height); nativeSize = new Size(width, height); } }
public static void setNewPos(IMediaSeeking mediaSeeking, long newPos, double fps) { if (mediaSeeking == null) return; if (!isInFrames(mediaSeeking)) newPos = frame2refTime(newPos,fps); mediaSeeking.SetPositions(newPos, AMSeekingSeekingFlags.AbsolutePositioning, null, AMSeekingSeekingFlags.NoPositioning); }
/// <summary> /// 解放 /// </summary> public virtual void Dispose() { try { Stop(); } catch (Exception) { } SampleGrabberCB.FrameSize = new Size(0, 0); SampleGrabberCB.Notify -= SampleGrabberCB_Notify; CaptureFilter = null; CaptureOutPin = null; SampleGrabber = null; SampleGrabberInPin = null; SampleGrabberOutPin = null; Renderer = null; RendererInPin = null; if (Seeking != null) { Marshal.ReleaseComObject(Seeking); } Seeking = null; if (GraphBuilder != null) { Marshal.ReleaseComObject(GraphBuilder); } GraphBuilder = null; }
private void InitGraph(string filename) { int hr = 0; //IntPtr hEvent; if (filename == string.Empty) { return; } this.filterGraph = new FilterGraph() as IFilterGraph2; #if DEBUG //rot = new DsROTEntry(this.filterGraph); #endif // Have the graph builder construct its the appropriate graph automatically hr = this.filterGraph.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); // QueryInterface for DirectShow interfaces this.mediaControl = this.filterGraph as IMediaControl; this.mediaSeeking = this.filterGraph as IMediaSeeking; //this.mediaEvent = this.graphBuilder as IMediaEvent; // Query for audio interfaces, which may not be relevant for video-only files this.basicAudio = this.filterGraph as IBasicAudio; // Complete window initialization this.currentPlaybackRate = 1.0; }
public CAviDS(string filename, double playSpeed) { builder = new FilterGraph() as IGraphBuilder; grabber = new SampleGrabber() as ISampleGrabber; mediaType = new AMMediaType(); mediaType.majorType = MediaType.Video; mediaType.subType = MediaSubType.RGB32; mediaType.formatType = FormatType.VideoInfo; DsError.ThrowExceptionForHR(grabber.SetMediaType(mediaType)); DsError.ThrowExceptionForHR(builder.AddFilter(grabber as IBaseFilter, "Sample Grabber(DTXMania)")); DsError.ThrowExceptionForHR(builder.RenderFile(filename, null)); CDirectShow.ConnectNullRendererFromSampleGrabber(builder, grabber as IBaseFilter); if (builder is IVideoWindow videoWindow) { videoWindow.put_AutoShow(OABool.False); } DsError.ThrowExceptionForHR(grabber.GetConnectedMediaType(mediaType)); videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader)); nWidth = videoInfo.BmiHeader.Width; nHeight = videoInfo.BmiHeader.Height; seeker = builder as IMediaSeeking; DsError.ThrowExceptionForHR(seeker.GetDuration(out nMediaLength)); DsError.ThrowExceptionForHR(seeker.SetRate(playSpeed / 20.0)); control = builder as IMediaControl; filter = builder as IMediaFilter; grabber.SetBufferSamples(BufferThem: true); Run(); Pause(); bPlaying = false; bPause = false; }
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); } }
/// <summary> /// Setup the IMediaSeeking interface /// </summary> protected void SetMediaSeekingInterface(IMediaSeeking mediaSeeking) { m_mediaSeeking = mediaSeeking; if (mediaSeeking == null) { CurrentPositionFormat = MediaPositionFormat.None; Duration = 0; return; } /* Get our prefered DirectShow TimeFormat */ Guid preferedFormat = ConvertPositionFormat(PreferedPositionFormat); /* Attempt to set the time format */ mediaSeeking.SetTimeFormat(preferedFormat); Guid currentFormat; /* Gets the current time format * we may not have been successful * setting our prefered format */ mediaSeeking.GetTimeFormat(out currentFormat); /* Set our property up with the right format */ CurrentPositionFormat = ConvertPositionFormat(currentFormat); SetDuration(); }
/// <summary> /// Open the file in <see cref="FilePath"/> and load it. /// </summary> private void OpenMediaFile() { ClosePlayer(); int hr = 0; this.graphBuilder = (IGraphBuilder) new FilterGraph(); hr = graphBuilder.RenderFile(this.FilePath, null); DsError.ThrowExceptionForHR(hr); this.mediaControl = (IMediaControl)this.graphBuilder; this.mediaEventEx = (IMediaEventEx)this.graphBuilder; this.mediaSeeking = (IMediaSeeking)this.graphBuilder; this.mediaPosition = (IMediaPosition)this.graphBuilder; this.videoWindow = this.graphBuilder as IVideoWindow; this.basicVideo = this.graphBuilder as IBasicVideo; int x, y; this.basicVideo.GetVideoSize(out x, out y); this.VideoSize = new Size(x, y); this.basicAudio = (IBasicAudio)this.graphBuilder; hr = this.mediaEventEx.SetNotifyWindow(notifyTarget, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_Owner(owner); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); videoWindow.SetWindowPosition(0, 0, Control.FromHandle(this.owner).Width, Control.FromHandle(this.owner).Height); double time; mediaPosition.get_Duration(out time); this.Length = (int)(time * 1000); this.State = PlayState.Opened; }
public void Close() { // store current volume so it persists from track to track if (loadedSong != null) { PreviousVolume = Volume; } Stop(); lock (lockingToken) { mediaEventEx = null; mediaSeeking = null; mediaControl = null; mediaPosition = null; basicAudio = null; if (this.graphBuilder != null) { Marshal.ReleaseComObject(this.graphBuilder); } this.graphBuilder = null; } loadedSong = null; _IsPlaying = false; }
private void Cleanup() { Log.Info("TSReader2MP4: cleanup"); if (_rotEntry != null) { _rotEntry.SafeDispose(); } _rotEntry = null; if (mediaControl != null) { mediaControl.Stop(); mediaControl = null; } fileWriterFilter = null; mediaSeeking = null; mediaEvt = null; mediaPos = null; mediaControl = null; if (h264Encoder != null) { DirectShowUtil.ReleaseComObject(h264Encoder); } h264Encoder = null; if (aacEncoder != null) { DirectShowUtil.ReleaseComObject(aacEncoder); } aacEncoder = null; if (mp4Muxer != null) { DirectShowUtil.ReleaseComObject(mp4Muxer); } mp4Muxer = null; if (AudioCodec != null) { DirectShowUtil.ReleaseComObject(AudioCodec); } AudioCodec = null; if (VideoCodec != null) { DirectShowUtil.ReleaseComObject(VideoCodec); } VideoCodec = null; if (tsreaderSource != null) { DirectShowUtil.ReleaseComObject(tsreaderSource); } tsreaderSource = null; DirectShowUtil.RemoveFilters(graphBuilder); if (graphBuilder != null) { DirectShowUtil.ReleaseComObject(graphBuilder); } graphBuilder = null; GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); }
/// <summary> create the used COM components and get the interfaces. </summary> private bool GetInterfaces() { Logger.Instance.Debug("AirplayerAudioPlayer: Get interfaces"); int iStage = 1; string audioDevice; using (Settings xmlreader = new MPSettings()) audioDevice = xmlreader.GetValueAsString("audioplayer", "sounddevice", "Default DirectSound Device"); //If user has bass as default player the default device is named slightly differently if (audioDevice == "Default Sound Device") { audioDevice = "Default DirectSound Device"; } Logger.Instance.Debug("AirplayerAudioPlayer: Using audio device '{0}'", audioDevice); int hr; try { graphBuilder = (IGraphBuilder) new FilterGraph(); iStage = 5; Utils.AddFilterByName(graphBuilder, DirectShow.FilterCategory.AudioRendererCategory, audioDevice); var sourceFilter = new GenericPushSourceFilter(settings.Source, settings.GetMediaType()); hr = graphBuilder.AddFilter(sourceFilter, sourceFilter.Name); new HRESULT(hr).Throw(); DSFilter source2 = new DSFilter(sourceFilter); hr = source2.OutputPin.Render(); new HRESULT(hr).Throw(); if (hr != 0) { Error.SetError("Unable to play file", "Missing codecs to play this file"); return(false); } iStage = 6; mediaCtrl = (IMediaControl)graphBuilder; iStage = 7; mediaEvt = (IMediaEventEx)graphBuilder; iStage = 8; mediaSeek = (IMediaSeeking)graphBuilder; iStage = 9; mediaPos = (IMediaPosition)graphBuilder; iStage = 10; basicAudio = graphBuilder as IBasicAudio; iStage = 11; Logger.Instance.Debug("AirplayerAudioPlayer: Interfaces created"); return(true); } catch (Exception ex) { Logger.Instance.Info("Can not start {0} stage:{1} err:{2} stack:{3}", m_strCurrentFile, iStage, ex.Message, ex.StackTrace); return(false); } }
public long NativeDuration() { // native duration with no limits applied long tDur = 0; IMediaSeeking pMS = m_pGraph as IMediaSeeking; int hr = pMS.GetDuration(out tDur); return(tDur); }
public static int getTotal(IMediaSeeking mediaSeeking, double fps) { if (mediaSeeking == null) return 1; long dur; mediaSeeking.GetDuration(out dur); if (!isInFrames(mediaSeeking)) dur = refTime2frame(dur,fps); return (int)dur; }
public long CurrentPosition() { // stream time in graph IMediaSeeking pMS = m_pGraph as IMediaSeeking; long tNow = 0; pMS.GetCurrentPosition(out tNow); return(tNow + m_tStart); }
/// <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; }
public override void releaseCOM() { if (!initialized) { return; } int hr = 0; // Stop previewing data if (this.mediaControl != null) { hr = this.mediaControl.Stop(); DsError.ThrowExceptionForHR(hr); hr = mediaControl.GetState(0, out FilterState state); DsError.ThrowExceptionForHR(hr); while (state != FilterState.Stopped) { System.Threading.Thread.Sleep(10); hr = mediaControl.GetState(0, out state); } } // Relinquish ownership (IMPORTANT!) of the video window. // Failing to call put_Owner can lead to assert failures within // the video renderer, as it still assumes that it has a valid // parent window. if (mediaeventEx != null) { mediaeventEx.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); mediaeventEx = null; } if (mediaControl != null) { Marshal.ReleaseComObject(this.mediaControl); this.mediaControl = null; } if (mediaPosition != null) { Marshal.ReleaseComObject(this.mediaPosition); this.mediaPosition = null; } if (mediaSeeking != null) { Marshal.ReleaseComObject(this.mediaSeeking); this.mediaSeeking = null; } if (basicAudio != null) { Marshal.ReleaseComObject(this.basicAudio); this.basicAudio = null; } if (this.graphBuilder2 != null) { //RemoveAllFilters(); Marshal.ReleaseComObject(this.graphBuilder2); this.graphBuilder2 = null; } SoundMasterControl.Instance.MovieVolumeChanged -= Instance_MovieVolumeChanged; this.initialized = false; GC.Collect(); GC.WaitForPendingFinalizers(); }
private void TearDownGraph() { #if DEBUG if (m_rot != null) { m_rot.Dispose(); m_rot = null; } #endif // Stop sending event messages if (m_pEvent != null) { m_pEvent.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); m_pEvent = null; } if (m_pControl != null) { m_pControl.Stop(); m_pControl = null; } if (m_pDisplay != null) { //Marshal.ReleaseComObject(m_pDisplay); m_pDisplay = null; } if (m_pMapper != null) { Marshal.ReleaseComObject(m_pMapper); m_pMapper = null; } if (m_pMixer != null) { Marshal.ReleaseComObject(m_pMixer); m_pMixer = null; } if (m_pEVR != null) { Marshal.ReleaseComObject(m_pEVR); m_pEVR = null; } if (m_pGraph != null) { Marshal.ReleaseComObject(m_pGraph); m_pGraph = null; } m_state = PlaybackState.Closed; m_seekCaps = 0; m_pSeek = null; }
//Play a specific shot public void PlayShot(int start, int stop) { long l_start = (long)start; long l_stop = (long)stop; IMediaSeeking i_media_seeking = m_FilterGraph as IMediaSeeking; i_media_seeking.SetTimeFormat(TimeFormat.Frame); i_media_seeking.SetPositions(l_start, DirectShowLib.AMSeekingSeekingFlags.AbsolutePositioning, l_stop, DirectShowLib.AMSeekingSeekingFlags.AbsolutePositioning); }
private void SetupGraph3(Control hWin, string FileName) { int hr; // Get the graphbuilder object m_FilterGraph = new FilterGraph() as IFilterGraph2; ICaptureGraphBuilder2 icgb2 = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); try { // Link the ICaptureGraphBuilder2 to the IFilterGraph2 hr = icgb2.SetFiltergraph(m_FilterGraph); DsError.ThrowExceptionForHR(hr); // Add the filters necessary to render the file. This function will // work with a number of different file types. IBaseFilter sourceFilter = null; hr = m_FilterGraph.AddSourceFilter(FileName, FileName, out sourceFilter); DsError.ThrowExceptionForHR(hr); IBaseFilter pAudioRenderer = (IBaseFilter) new DSoundRender(); hr = m_FilterGraph.AddFilter(pAudioRenderer, "Audio Renderer"); DsError.ThrowExceptionForHR(hr); // Connect the pieces together, use the default renderer hr = icgb2.RenderStream(null, null, sourceFilter, null, null); DsError.ThrowExceptionForHR(hr); hr = icgb2.RenderStream(null, MediaType.Audio, sourceFilter, null, pAudioRenderer); DsError.ThrowExceptionForHR(hr); // Configure the Video Window IVideoWindow videoWindow = m_FilterGraph as IVideoWindow; ConfigureVideoWindow(videoWindow, hWin); // Grab some other interfaces m_mediaEvent = m_FilterGraph as IMediaEvent; m_mediaCtrl = m_FilterGraph as IMediaControl; m_mediaSeeking = m_FilterGraph as IMediaSeeking; m_basicAudio = m_FilterGraph as IBasicAudio; } 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 }
//Ctrl'event private void btnPlay_Click(object sender, EventArgs e) { int hr = 0; if (this.graphBuilder == null) { string filename = txtPath.Text; this.graphBuilder = (IGraphBuilder) new FilterGraph(); 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; hr = this.mediaEventEx.SetNotifyWindow(this.Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); //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); this.Focus(); hr = InitVideoWindow(1, 1); DsError.ThrowExceptionForHR(hr); double time; mediaPosition.get_Duration(out time); trackBar1.SetRange(0, (int)time); //create a new Thread t = new Thread(new ThreadStart(updateTimeBarThread)); if (btnPlay.Text.Equals("Play")) { hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); btnPlay.Text = "Pause"; } else { hr = this.mediaControl.Pause(); DsError.ThrowExceptionForHR(hr); btnPlay.Text = "Play"; } } }
//Reset: start position is 0, end position is the last frame, needed after playshot public void Reset() { IMediaSeeking i_media_seeking = m_FilterGraph as IMediaSeeking; i_media_seeking.SetTimeFormat(TimeFormat.Frame); long endFrame = 0; int test = i_media_seeking.GetDuration(out endFrame); i_media_seeking.SetPositions(0, DirectShowLib.AMSeekingSeekingFlags.AbsolutePositioning, endFrame, DirectShowLib.AMSeekingSeekingFlags.AbsolutePositioning); }
/// <summary> /// Creates a new instance of the Seeking Graph /// </summary> public SeekingGraph() : base() { _mediaSeeking = (IMediaSeeking)graph; _mediaPosition = (IMediaPosition)graph; _mediaEvent = (IMediaEventEx)graph; _mediaSeekTimer = new Timer(); _mediaSeekTimer.Interval = MediaSeekTimerInterval; _mediaSeekTimer.Elapsed += new ElapsedEventHandler(NotifyPlaybackPositionChanged); }
public static int getCurPos(IMediaSeeking mediaSeeking, double fps) { if (mediaSeeking == null) return 1; long cur; mediaSeeking.GetCurrentPosition(out cur); if (!isInFrames(mediaSeeking)) cur = refTime2frame(cur,fps); return (int)cur; }
private void Cleanup() { Log.Info("DVR2MPG: cleanup"); if (_rotEntry != null) { _rotEntry.SafeDispose(); } _rotEntry = null; if (mediaControl != null) { mediaControl.Stop(); mediaControl = null; } mediaSeeking = null; mediaEvt = null; mediaControl = null; if (powerDvdMuxer != null) DirectShowUtil.ReleaseComObject(powerDvdMuxer); powerDvdMuxer = null; if (fileWriterFilter != null) DirectShowUtil.ReleaseComObject(fileWriterFilter); fileWriterFilter = null; if (bufferSource != null) DirectShowUtil.ReleaseComObject(bufferSource); bufferSource = null; DirectShowUtil.RemoveFilters(graphBuilder); if (graphBuilder != null) DirectShowUtil.ReleaseComObject(graphBuilder); graphBuilder = null; }
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 { } }
/// <summary> Shut down capture </summary> private void CloseInterfaces() { int hr; try { if (m_handle != IntPtr.Zero) { Marshal.FreeCoTaskMem(m_handle); m_handle = IntPtr.Zero; } } catch (Exception) { } try { if (mediaControl != null) { // Stop the graph hr = mediaControl.Stop(); mediaControl = null; } } catch (Exception ex) { Debug.WriteLine(ex); } #if DEBUG if (m_rot != null) { m_rot.Dispose(); } #endif if (this.mediaSeeking != null) this.mediaSeeking = null; if (this.frameStep != null) this.frameStep = null; if (this.sampleGrabber != null) { Marshal.ReleaseComObject(this.sampleGrabber); this.sampleGrabber = null; } if (nullrenderer != null) { Marshal.ReleaseComObject(nullrenderer); nullrenderer = null; } if (graphBuilder != null) { Marshal.ReleaseComObject(graphBuilder); graphBuilder = null; } GC.Collect(); }
/// <summary> /// グラフの生成 /// </summary> public virtual void Setup() { this.Dispose(); try { // グラフ. // CoCreateInstance GraphBuilder = (IGraphBuilder)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(GUID.CLSID_FilterGraph))); #region フィルタ追加. // ファイル入力. IBaseFilter capture = null; GraphBuilder.AddSourceFilter(SourceFile, "CaptureFilter", ref capture); if (capture == null) throw new System.IO.IOException(); #if false // DMO ラッパーフィルタ. // https://msdn.microsoft.com/ja-jp/library/cc371140.aspx IBaseFilter dmo = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(GUID.CLSID_DMOWrapperFilter))); if (dmo != null) { //// Mpeg4 Decoder DMO //// F371728A-6052-4D47-827C-D039335DFE0A //// 4A69B442-28BE-4991-969C-B500ADF5D8A8 //// mpg4decd.dll [C:\Windows\System32, C:\Windows\SysWOW64] var idmo = (IDMOWrapperFilter)dmo; idmo.Init(new Guid("F371728A-6052-4D47-827C-D039335DFE0A"), new Guid("4A69B442-28BE-4991-969C-B500ADF5D8A8")); idmo = null; this.GraphBuilder.AddFilter(dmo, "Mpeg4 Decoder DMO"); } #endif #if false // Avi Splitter IBaseFilter splitter = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(GUID.CLSID_AVISplitter))); if (splitter == null) throw new System.IO.IOException(); this.GraphBuilder.AddFilter(splitter, "Avi Splitter"); // Avi Decompressor IBaseFilter decompressor = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(GUID.CLSID_AVIDec))); if (decompressor == null) throw new System.IO.IOException(); this.GraphBuilder.AddFilter(decompressor, "Avi Decompressor"); #endif // サンプルグラバー. IBaseFilter grabber = (IBaseFilter)CreateSampleGrabber(); if (grabber == null) throw new System.IO.IOException(); this.GraphBuilder.AddFilter(grabber, "SampleGrabber"); // レンダラー. IBaseFilter renderer = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(GUID.CLSID_NullRenderer))); if (renderer == null) throw new System.IO.IOException(); this.GraphBuilder.AddFilter(renderer, "Renderer"); #endregion #region ピンの取得. IPin capture_out = DSLab.Axi.FindPin(capture, 0, PIN_DIRECTION.PINDIR_OUTPUT); IPin grabber_in = DSLab.Axi.FindPin(grabber, 0, PIN_DIRECTION.PINDIR_INPUT); IPin grabber_out = DSLab.Axi.FindPin(grabber, 0, PIN_DIRECTION.PINDIR_OUTPUT); IPin renderer_in = DSLab.Axi.FindPin(renderer, 0, PIN_DIRECTION.PINDIR_INPUT); #endregion #region ピンの接続. GraphBuilder.Connect(capture_out, grabber_in); GraphBuilder.Connect(grabber_out, renderer_in); #endregion #region 保管: インターフェース. CaptureFilter = capture; CaptureOutPin = capture_out; SampleGrabber = (ISampleGrabber)grabber; SampleGrabberInPin = grabber_in; SampleGrabberOutPin = grabber_out; Renderer = renderer; RendererInPin = renderer_in; #endregion #region 保管: フレームサイズ. VIDEOINFOHEADER vinfo = DSLab.Axi.GetVideoInfo(SampleGrabber); this.SampleGrabberCB.BitmapInfo = vinfo.bmiHeader; this.SampleGrabberCB.FrameSize = new Size( System.Math.Abs(this.SampleGrabberCB.BitmapInfo.biWidth), System.Math.Abs(this.SampleGrabberCB.BitmapInfo.biHeight) ); #endregion #region インタフェースの抽出: { DSLab.IGraphBuilder graph = this.GraphBuilder; DSLab.IEnumFilters filters = null; DSLab.IBaseFilter filter = null; int fetched = 0; int hr = graph.EnumFilters(ref filters); while (filters.Next(1, ref filter, ref fetched) == (int)DSLab.HRESULT.S_OK) { if (fetched == 0) break; if (filter is DSLab.IMediaSeeking) { // シーク操作用. Seeking = (DSLab.IMediaSeeking)filter; } else { // フィルタ解放. Marshal.ReleaseComObject(filter); filter = null; } } // 解放. Marshal.ReleaseComObject(filters); } #endregion // DEBUG #if DEBUG DebugPrint(this.GraphBuilder); #endif } catch (Exception ex) { throw new DSLab.CxDSException(ex); } }
// // 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 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); } }
/// <summary> create the used COM components and get the interfaces. </summary> protected virtual bool GetDVDInterfaces(string path) { int hr; //Type comtype = null; object comobj = null; _freeNavigator = true; _dvdInfo = null; _dvdCtrl = null; bool useAC3Filter = false; string dvdNavigator = ""; string aspectRatioMode = ""; string displayMode = ""; _videoPref = DvdPreferredDisplayMode.DisplayContentDefault; using (MediaPortal.Profile.Settings xmlreader = new MPSettings()) { dvdNavigator = xmlreader.GetValueAsString("dvdplayer", "navigator", "DVD Navigator"); aspectRatioMode = xmlreader.GetValueAsString("dvdplayer", "armode", "").ToLower(); dvdNavigator = "dslibdvdnav"; if (aspectRatioMode == "crop") { arMode = AspectRatioMode.Crop; } if (aspectRatioMode == "letterbox") { arMode = AspectRatioMode.LetterBox; } if (aspectRatioMode == "stretch") { arMode = AspectRatioMode.Stretched; } //if ( aspectRatioMode == "stretch" ) arMode = AspectRatioMode.zoom14to9; if (aspectRatioMode == "follow stream") { arMode = AspectRatioMode.StretchedAsPrimary; } useAC3Filter = xmlreader.GetValueAsBool("dvdplayer", "ac3", false); displayMode = xmlreader.GetValueAsString("dvdplayer", "displaymode", "").ToLower(); if (displayMode == "default") { _videoPref = DvdPreferredDisplayMode.DisplayContentDefault; } if (displayMode == "16:9") { _videoPref = DvdPreferredDisplayMode.Display16x9; } if (displayMode == "4:3 pan scan") { _videoPref = DvdPreferredDisplayMode.Display4x3PanScanPreferred; } if (displayMode == "4:3 letterbox") { _videoPref = DvdPreferredDisplayMode.Display4x3LetterBoxPreferred; } } try { _dvdGraph = (IDvdGraphBuilder)new DvdGraphBuilder(); hr = _dvdGraph.GetFiltergraph(out _graphBuilder); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } _rotEntry = new DsROTEntry((IFilterGraph)_graphBuilder); _vmr9Filter = (IBaseFilter)new VideoMixingRenderer9(); IVMRFilterConfig9 config = _vmr9Filter as IVMRFilterConfig9; hr = config.SetNumberOfStreams(1); hr = config.SetRenderingMode(VMR9Mode.Windowless); windowlessCtrl = (IVMRWindowlessControl9)_vmr9Filter; windowlessCtrl.SetVideoClippingWindow(this.panVideoWin.Handle); // config.SetRenderingPrefs(VMR9RenderPrefs. _graphBuilder.AddFilter(_vmr9Filter, "Video Mixing Renderer 9"); // _vmr7 = new VMR7Util(); // _vmr7.AddVMR7(_graphBuilder); try { _dvdbasefilter = DirectShowUtil.AddFilterToGraph(_graphBuilder, dvdNavigator); if (_dvdbasefilter != null) { IDvdControl2 cntl = (IDvdControl2)_dvdbasefilter; if (cntl != null) { _dvdInfo = (IDvdInfo2)cntl; _dvdCtrl = (IDvdControl2)cntl; if (path != null) { if (path.Length != 0) { cntl.SetDVDDirectory(path); } } _dvdCtrl.SetOption(DvdOptionFlag.HMSFTimeCodeEvents, true); // use new HMSF timecode format _dvdCtrl.SetOption(DvdOptionFlag.ResetOnStop, false); AddPreferedCodecs(_graphBuilder); DirectShowUtil.RenderOutputPins(_graphBuilder, _dvdbasefilter); // _videoWin = _graphBuilder as IVideoWindow; _freeNavigator = false; } //DirectShowUtil.ReleaseComObject( _dvdbasefilter); _dvdbasefilter = null; } } catch (Exception ex) { string strEx = ex.Message; } Guid riid; if (_dvdInfo == null) { riid = typeof(IDvdInfo2).GUID; hr = _dvdGraph.GetDvdInterface(riid, out comobj); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } _dvdInfo = (IDvdInfo2)comobj; comobj = null; } if (_dvdCtrl == null) { riid = typeof(IDvdControl2).GUID; hr = _dvdGraph.GetDvdInterface(riid, out comobj); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } _dvdCtrl = (IDvdControl2)comobj; comobj = null; } _mediaCtrl = (IMediaControl)_graphBuilder; _mediaEvt = (IMediaEventEx)_graphBuilder; _basicAudio = _graphBuilder as IBasicAudio; _mediaPos = (IMediaPosition)_graphBuilder; _mediaSeek = (IMediaSeeking)_graphBuilder; _mediaStep = (IVideoFrameStep)_graphBuilder; _basicVideo = _graphBuilder as IBasicVideo2; _videoWin = _graphBuilder as IVideoWindow; // disable Closed Captions! IBaseFilter baseFilter; _graphBuilder.FindFilterByName("Line 21 Decoder", out baseFilter); if (baseFilter == null) { _graphBuilder.FindFilterByName("Line21 Decoder", out baseFilter); } if (baseFilter != null) { _line21Decoder = (IAMLine21Decoder)baseFilter; if (_line21Decoder != null) { AMLine21CCState state = AMLine21CCState.Off; hr = _line21Decoder.SetServiceState(state); if (hr == 0) { logger.Info("DVDPlayer:Closed Captions disabled"); } else { logger.Info("DVDPlayer:failed 2 disable Closed Captions"); } } } /* // get video window if (_videoWin==null) { riid = typeof( IVideoWindow ).GUID; hr = _dvdGraph.GetDvdInterface( ref riid, out comobj ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); _videoWin = (IVideoWindow) comobj; comobj = null; } */ // GetFrameStepInterface(); DirectShowUtil.SetARMode(_graphBuilder, arMode); DirectShowUtil.EnableDeInterlace(_graphBuilder); //m_ovMgr = new OVTOOLLib.OvMgrClass(); //m_ovMgr.SetGraph(_graphBuilder); return true; } catch (Exception) { //MessageBox.Show( this, "Could not get interfaces\r\n" + ee.Message, "DVDPlayer.NET", MessageBoxButtons.OK, MessageBoxIcon.Stop ); CloseDVDInterfaces(); return false; } finally { if (comobj != null) { DirectShowUtil.ReleaseComObject(comobj); } comobj = null; } }
/// <summary> do cleanup and release DirectShow. </summary> protected virtual void CloseDVDInterfaces() { if (_graphBuilder == null) { return; } int hr; try { logger.Info("DVDPlayer:cleanup DShow graph"); if (_mediaCtrl != null) { hr = _mediaCtrl.Stop(); _mediaCtrl = null; } _state = PlayState.Stopped; _mediaEvt = null; _visible = false; _videoWin = null; // videoStep = null; _dvdCtrl = null; _dvdInfo = null; _basicVideo = null; _basicAudio = null; _mediaPos = null; _mediaSeek = null; _mediaStep = null; //if (_vmr7 != null) //{ // _vmr7.RemoveVMR7(); //} //_vmr7 = null; if (_vmr9Filter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_vmr9Filter)) > 0) { ; } _vmr9Filter = null; } if (_dvdbasefilter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_dvdbasefilter)) > 0) { ; } _dvdbasefilter = null; } if (_cmdOption != null) { DirectShowUtil.ReleaseComObject(_cmdOption); } _cmdOption = null; _pendingCmd = false; if (_line21Decoder != null) { while ((hr = DirectShowUtil.ReleaseComObject(_line21Decoder)) > 0) { ; } _line21Decoder = null; } if (_graphBuilder != null) { DirectShowUtil.RemoveFilters(_graphBuilder); if (_rotEntry != null) { _rotEntry.Dispose(); _rotEntry = null; } while ((hr = DirectShowUtil.ReleaseComObject(_graphBuilder)) > 0) { ; } _graphBuilder = null; } if (_dvdGraph != null) { while ((hr = DirectShowUtil.ReleaseComObject(_dvdGraph)) > 0) { ; } _dvdGraph = null; } _state = PlayState.Init; } catch (Exception ex) { logger.Error("DVDPlayer:exception while cleanuping DShow graph {0} {1}", ex.Message, ex.StackTrace); } }
public bool Transcode(TranscodeInfo info, MediaPortal.Core.Transcoding.VideoFormat format, MediaPortal.Core.Transcoding.Quality quality, Standard standard) { if (!Supports(format)) return false; string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLower() != ".dvr-ms" && ext.ToLower() != ".sbe") return false; //Type comtype = null; //object comobj = null; try { Log.Info("DVR2MPG: create graph"); graphBuilder = (IGraphBuilder)new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("DVR2MPG: add streambuffersource"); bufferSource = (IStreamBufferSource)new StreamBufferSource(); IBaseFilter filter = (IBaseFilter)bufferSource; graphBuilder.AddFilter(filter, "SBE SOURCE"); Log.Info("DVR2MPG: load file:{0}", info.file); IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource; int hr = fileSource.Load(info.file, null); Log.Info("DVR2MPG: Add Cyberlink MPEG2 multiplexer to graph"); string monikerPowerDvdMuxer = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{7F2BBEAF-E11C-4D39-90E8-938FB5A86045}"; powerDvdMuxer = Marshal.BindToMoniker(monikerPowerDvdMuxer) as IBaseFilter; if (powerDvdMuxer == null) { Log.Warn("DVR2MPG: FAILED:Unable to create Cyberlink MPEG Muxer (PowerDVD)"); Cleanup(); return false; } hr = graphBuilder.AddFilter(powerDvdMuxer, "PDR MPEG Muxer"); if (hr != 0) { Log.Warn("DVR2MPG: FAILED:Add Cyberlink MPEG Muxer to filtergraph :0x{0:X}", hr); Cleanup(); return false; } //add filewriter Log.Info("DVR2MPG: Add FileWriter to graph"); string monikerFileWrite = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{3E8868CB-5FE8-402C-AA90-CB1AC6AE3240}"; IBaseFilter fileWriterbase = Marshal.BindToMoniker(monikerFileWrite) as IBaseFilter; if (fileWriterbase == null) { Log.Warn("DVR2MPG: FAILED:Unable to create FileWriter"); Cleanup(); return false; } fileWriterFilter = fileWriterbase as IFileSinkFilter; if (fileWriterFilter == null) { Log.Warn("DVR2MPG: FAILED:Add unable to get IFileSinkFilter for filewriter"); Cleanup(); return false; } hr = graphBuilder.AddFilter(fileWriterbase, "FileWriter"); if (hr != 0) { Log.Warn("DVR2MPG: FAILED:Add FileWriter to filtergraph :0x{0:X}", hr); Cleanup(); return false; } //connect output #0 of streambuffer source->powerdvd audio in //connect output #1 of streambuffer source->powerdvd video in Log.Info("DVR2MPG: connect streambuffer->multiplexer"); IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0); pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1); pinIn0 = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Input, 0); pinIn1 = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Input, 1); if (pinOut0 == null || pinOut1 == null || pinIn0 == null || pinIn1 == null) { Log.Warn("DVR2MPG: FAILED:unable to get pins of muxer&source"); Cleanup(); return false; } bool usingAc3 = false; AMMediaType amAudio = new AMMediaType(); amAudio.majorType = MediaType.Audio; amAudio.subType = MediaSubType.Mpeg2Audio; hr = pinOut0.Connect(pinIn1, amAudio); if (hr != 0) { amAudio.subType = MediaSubType.DolbyAC3; hr = pinOut0.Connect(pinIn1, amAudio); usingAc3 = true; } if (hr != 0) { Log.Warn("DVR2MPG: FAILED: unable to connect audio pins: 0x{0:X}", hr); Cleanup(); return false; } if (usingAc3) Log.Info("DVR2MPG: using AC3 audio"); else Log.Info("DVR2MPG: using MPEG audio"); AMMediaType amVideo = new AMMediaType(); amVideo.majorType = MediaType.Video; amVideo.subType = MediaSubType.Mpeg2Video; hr = pinOut1.Connect(pinIn0, amVideo); if (hr != 0) { Log.Warn("DVR2MPG: FAILED: unable to connect video pins: 0x{0:X}", hr); Cleanup(); return false; } //connect output of powerdvd muxer->input of filewriter Log.Info("DVR2MPG: connect multiplexer->filewriter"); IPin pinOut, pinIn; pinOut = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Output, 0); if (pinOut == null) { Log.Warn("DVR2MPG: FAILED:cannot get output pin of Cyberlink MPEG muxer :0x{0:X}", hr); Cleanup(); return false; } pinIn = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 0); if (pinIn == null) { Log.Warn("DVR2MPG: FAILED:cannot get input pin of Filewriter :0x{0:X}", hr); Cleanup(); return false; } AMMediaType mt = new AMMediaType(); hr = pinOut.Connect(pinIn, mt); if (hr != 0) { Log.Warn("DVR2MPG: FAILED:connect muxer->filewriter :0x{0:X}", hr); Cleanup(); return false; } //set output filename string outputFileName = System.IO.Path.ChangeExtension(info.file, ".mpg"); Log.Info("DVR2MPG: set output file to :{0}", outputFileName); mt.majorType = MediaType.Stream; mt.subType = MediaSubTypeEx.MPEG2; hr = fileWriterFilter.SetFileName(outputFileName, mt); if (hr != 0) { Log.Warn("DVR2MPG: FAILED:unable to set filename for filewriter :0x{0:X}", hr); Cleanup(); return false; } mediaControl = graphBuilder as IMediaControl; mediaSeeking = graphBuilder as IMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; Log.Info("DVR2MPG: start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Warn("DVR2MPG: FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return false; } } catch (Exception ex) { Log.Error("DVR2MPG: Unable create graph: {0}", ex.Message); Cleanup(); return false; } return true; }
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> /// Frees any allocated or unmanaged resources /// </summary> protected override void FreeResources() { base.FreeResources(); if (m_mediaSeeking != null) Marshal.ReleaseComObject(m_mediaSeeking); m_mediaSeeking = null; m_currentPosition = 0; Duration = 0; InvokeMediaPositionChanged(null); }
private void CloseInterfaces() { try { lock (this) { #if DEBUG if (rot != null) { rot.Dispose(); rot = null; } #endif //ChangeState(PlayState.Exiting); //// Release the thread (if the thread was started) //if (this.currentState != PlayState.Exiting) //{ // this.currentState = PlayState.Exiting; // if (this.manualResetEvent != null) // { // manualResetEvent.Set(); // manualResetEvent.SafeWaitHandle.Dispose(); // manualResetEvent.Close(); // manualResetEvent = null; // } //} //if (eventThread != null) //{ // eventThread.Abort(); //} // Release and zero DirectShow interfaces if (this.mediaSeeking != null) this.mediaSeeking = null; //if (this.mediaEvent != null) // this.mediaEvent = null; if (this.mediaControl != null) this.mediaControl = null; if (this.basicAudio != null) this.basicAudio = null; if (this.filterGraph != null) { //// End event thread. //int hr = ((IMediaEventSink)this.filterGraph).Notify(EventCode.UserAbort, IntPtr.Zero, IntPtr.Zero); //DsError.ThrowExceptionForHR(hr); ////EventCode code; ////hr = ((IMediaEvent)this.filterGraph).WaitForCompletion(0, out code); ////DsError.ThrowExceptionForHR(hr); //while (!threadCompleted) //{ // Thread.Sleep(2); //} Marshal.ReleaseComObject(this.filterGraph); } this.filterGraph = null; GC.Collect(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Exception occured"); } }
/// <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> build the capture graph for grabber. </summary> private void SetupGraph(string FileName) { int hr; // Get the graphbuilder object this.graphBuilder = new FilterGraph() as IGraphBuilder; this.mediaControl = this.graphBuilder as IMediaControl; this.mediaSeeking = this.graphBuilder as IMediaSeeking; this.mediaEvent = this.graphBuilder as IMediaEvent; try { // Get the SampleGrabber interface this.sampleGrabber = new SampleGrabber() as ISampleGrabber; this.sampleGrabberFilter = sampleGrabber as IBaseFilter; ConfigureSampleGrabber(sampleGrabber); // Add the frame grabber to the graph hr = graphBuilder.AddFilter(sampleGrabberFilter, "Ds.NET Sample Grabber"); DsError.ThrowExceptionForHR(hr); IBaseFilter aviSplitter = new AviSplitter() as IBaseFilter; // Add the aviSplitter to the graph hr = graphBuilder.AddFilter(aviSplitter, "Splitter"); DsError.ThrowExceptionForHR(hr); // Have the graph builder construct its appropriate graph automatically hr = this.graphBuilder.RenderFile(FileName, null); DsError.ThrowExceptionForHR(hr); #if DEBUG m_rot = new DsROTEntry(graphBuilder); #endif // Remove the video renderer filter IBaseFilter defaultVideoRenderer = null; graphBuilder.FindFilterByName("Video Renderer", out defaultVideoRenderer); graphBuilder.RemoveFilter(defaultVideoRenderer); // Disconnect anything that is connected // to the output of the sample grabber IPin iPinSampleGrabberOut = DsFindPin.ByDirection(sampleGrabberFilter, PinDirection.Output, 0); IPin iPinVideoIn; hr = iPinSampleGrabberOut.ConnectedTo(out iPinVideoIn); if (hr == 0) { // Disconnect the sample grabber output from the attached filters hr = iPinVideoIn.Disconnect(); DsError.ThrowExceptionForHR(hr); hr = iPinSampleGrabberOut.Disconnect(); DsError.ThrowExceptionForHR(hr); } else { // Try other way round because automatic renderer could not build // graph including the sample grabber IPin iPinAVISplitterOut = DsFindPin.ByDirection(aviSplitter, PinDirection.Output, 0); IPin iPinAVISplitterIn; hr = iPinAVISplitterOut.ConnectedTo(out iPinAVISplitterIn); DsError.ThrowExceptionForHR(hr); hr = iPinAVISplitterOut.Disconnect(); DsError.ThrowExceptionForHR(hr); hr = iPinAVISplitterIn.Disconnect(); DsError.ThrowExceptionForHR(hr); // Connect the avi splitter output to sample grabber IPin iPinSampleGrabberIn = DsFindPin.ByDirection(sampleGrabberFilter, PinDirection.Input, 0); hr = graphBuilder.Connect(iPinAVISplitterOut, iPinSampleGrabberIn); DsError.ThrowExceptionForHR(hr); } // Add the null renderer to the graph nullrenderer = new NullRenderer() as IBaseFilter; hr = graphBuilder.AddFilter(nullrenderer, "Null renderer"); DsError.ThrowExceptionForHR(hr); // Get the input pin of the null renderer IPin iPinNullRendererIn = DsFindPin.ByDirection(nullrenderer, PinDirection.Input, 0); // Connect the sample grabber to the null renderer hr = graphBuilder.Connect(iPinSampleGrabberOut, iPinNullRendererIn); DsError.ThrowExceptionForHR(hr); // Read and cache the image sizes SaveSizeInfo(sampleGrabber); this.GetFrameStepInterface(); } finally { } }
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"); } }
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); }
/// <summary> /// 解放 /// </summary> public virtual void Dispose() { try { Stop(); } catch (Exception) { } SampleGrabberCB.FrameSize = new Size(0, 0); SampleGrabberCB.Notify -= SampleGrabberCB_Notify; CaptureFilter = null; CaptureOutPin = null; SampleGrabber = null; SampleGrabberInPin = null; SampleGrabberOutPin = null; Renderer = null; RendererInPin = null; if (Seeking != null) Marshal.ReleaseComObject(Seeking); Seeking = null; if (GraphBuilder != null) Marshal.ReleaseComObject(GraphBuilder); GraphBuilder = 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 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 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); } }
private void InitGraph(string filename) { int hr = 0; //IntPtr hEvent; if (filename == string.Empty) return; this.filterGraph = new FilterGraph() as IFilterGraph2; #if DEBUG //rot = new DsROTEntry(this.filterGraph); #endif // Have the graph builder construct its the appropriate graph automatically hr = this.filterGraph.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); // QueryInterface for DirectShow interfaces this.mediaControl = this.filterGraph as IMediaControl; this.mediaSeeking = this.filterGraph as IMediaSeeking; //this.mediaEvent = this.graphBuilder as IMediaEvent; // Query for audio interfaces, which may not be relevant for video-only files this.basicAudio = this.filterGraph as IBasicAudio; // Complete window initialization this.currentPlaybackRate = 1.0; }
protected bool GetInterfaces(string filename, int titleBD) { try { Log.Debug("BDPlayer: GetInterfaces()"); _graphBuilder = (IGraphBuilder)new FilterGraph(); _rotEntry = new DsROTEntry(_graphBuilder as IFilterGraph); filterConfig = GetFilterConfiguration(); if (filterConfig.AudioRenderer.Length > 0) { _audioRendererFilter = DirectShowUtil.AddAudioRendererToGraph(_graphBuilder, filterConfig.AudioRenderer, true); } BDReader reader = new BDReader(); _interfaceBDReader = reader as IBaseFilter; _ireader = reader as IBDReader; if (_interfaceBDReader == null || _ireader == null) { // todo: add exception return false; } // add the BD reader int hr = _graphBuilder.AddFilter(_interfaceBDReader, BD_READER_GRAPH_NAME); DsError.ThrowExceptionForHR(hr); Log.Debug("BDPlayer: Add BDReader to graph"); IFileSourceFilter interfaceFile = (IFileSourceFilter)_interfaceBDReader; LoadSettings(_ireader); _ireader.SetD3DDevice(DirectShowUtil.GetUnmanagedDevice(GUIGraphicsContext.DX9Device)); _ireader.SetBDReaderCallback(this); hr = interfaceFile.Load(filename, null); DsError.ThrowExceptionForHR(hr); Log.Debug("BDPlayer: BDReader loaded: {0}", filename); List<TitleInfo> titles = GetTitleInfoCollection(_ireader); while (true) { if (g_Player.ForcePlay && g_Player.SetResumeBDTitleState < g_Player.BdDefaultTitle) { if (titles.Count == 1) { _titleToPlay = 0; g_Player.SetResumeBDTitleState = g_Player.BdRemuxTitle; } else { _titleToPlay = g_Player.SetResumeBDTitleState; } _forceTitle = true; g_Player.ForcePlay = false; } else { if (titles.Count == 1) { // BD has only one title (remux one) _forceTitle = true; _titleToPlay = 0; g_Player.SetResumeBDTitleState = g_Player.BdRemuxTitle; if (g_Player.SetResumeBDTitleState == -1) { // user cancelled dialog titles.Dispose(); g_Player.Stop(); return false; } } else { _titleToPlay = SelectTitle(titles); g_Player.SetResumeBDTitleState = _titleToPlay; Log.Info("BDPlayer: BDReader _titleToPlay : {0}", _titleToPlay); if (_titleToPlay > -1) { // a specific title was selected _forceTitle = true; if (g_Player.SetResumeBDTitleState == -1) { // user cancelled dialog titles.Dispose(); g_Player.Stop(); return false; } } else { if (_titleToPlay == -1) { // user cancelled dialog g_Player.Stop(); titles.Dispose(); return false; } // user choose to display menu _forceTitle = false; } } } _ireader.ForceTitleBasedPlayback(_forceTitle, (uint)_titleToPlay); Log.Debug("BDPlayer: Starting BDReader"); eventBuffer.Clear(); hr = _ireader.Start(); if (hr != 0) { if (!_forceTitle) { Log.Error("BDPlayer: Failed to start file:{0} :0x{1:x}", filename, hr); continue; } Log.Error("BDPlayer: Failed to start in title based mode file:{0} :0x{1:x}", filename, hr); titles.Dispose(); return false; } else { Log.Info("BDPlayer: BDReader started"); } break; } titles.Dispose(); #region Filters Log.Info("BDPlayer: Adding filters"); _vmr9 = new VMR9Util(); _vmr9.AddVMR9(_graphBuilder); _vmr9.Enable(false); // Set VideoDecoder and VC1Override before adding filter in graph SetVideoDecoder(); SetVC1Override(); // Add preferred video filters UpdateFilters("Video"); // Add preferred audio filters UpdateFilters("Audio"); // Let the subtitle engine handle the proper filters try { SubtitleRenderer.GetInstance().AddSubtitleFilter(_graphBuilder); } catch (Exception e) { Log.Error(e); } #endregion #region PostProcessingEngine Detection IPostProcessingEngine postengine = PostProcessingEngine.GetInstance(true); if (!postengine.LoadPostProcessing(_graphBuilder)) { PostProcessingEngine.engine = new PostProcessingEngine.DummyEngine(); } #endregion #region render BDReader output pins Log.Info("BDPlayer: Render BDReader outputs"); if (_interfaceBDReader != null) { DirectShowUtil.RenderGraphBuilderOutputPins(_graphBuilder, _interfaceBDReader); } //remove InternalScriptRenderer as it takes subtitle pin disableISR(); //disable Closed Captions! disableCC(); //RemoveAudioR(); DirectShowUtil.RemoveUnusedFiltersFromGraph(_graphBuilder); #endregion _mediaCtrl = (IMediaControl)_graphBuilder; _mediaEvt = (IMediaEventEx)_graphBuilder; _mediaSeeking = (IMediaSeeking)_graphBuilder; try { SubtitleRenderer.GetInstance().SetPlayer(this); _dvbSubRenderer = SubtitleRenderer.GetInstance(); } catch (Exception e) { Log.Error(e); } _subtitleStream = (Player.TSReaderPlayer.ISubtitleStream)_interfaceBDReader; if (_subtitleStream == null) { Log.Error("BDPlayer: Unable to get ISubtitleStream interface"); } // if only dvb subs are enabled, pass null for ttxtDecoder _subSelector = new SubtitleSelector(_subtitleStream, _dvbSubRenderer, null); EnableSubtitle = _subtitlesEnabled; //Sync Audio Renderer SyncAudioRenderer(); if (!_vmr9.IsVMR9Connected) { Log.Error("BDPlayer: Failed vmr9 not connected"); return false; } _vmr9.SetDeinterlaceMode(); return true; } catch (Exception ex) { Log.Error("BDPlayer: Exception while creating DShow graph {0}", ex.Message); return false; } }
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); }
/// <summary> do cleanup and release DirectShow. </summary> protected void CloseInterfaces() { if (_graphBuilder == null) { return; } int hr; Log.Debug("BDPlayer: Cleanup DShow graph {0}", GUIGraphicsContext.InVmr9Render); try { BDOSDRenderer.Release(); if (_mediaCtrl != null) { int counter = 0; FilterState state; hr = _mediaCtrl.Stop(); hr = _mediaCtrl.GetState(10, out state); while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render) { Thread.Sleep(100); hr = _mediaCtrl.GetState(10, out state); counter++; if (counter >= 30) { if (state != FilterState.Stopped) Log.Error("BDPlayer: graph still running"); if (GUIGraphicsContext.InVmr9Render) Log.Error("BDPlayer: in renderer"); break; } } _mediaCtrl = null; } if (_vmr9 != null) { _vmr9.Enable(false); } if (_mediaEvt != null) { hr = _mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); _mediaEvt = null; } _videoWin = _graphBuilder as IVideoWindow; if (_videoWin != null) { hr = _videoWin.put_Visible(OABool.False); hr = _videoWin.put_Owner(IntPtr.Zero); _videoWin = null; } _mediaSeeking = null; _basicAudio = null; _basicVideo = null; _ireader = null; #region Cleanup Sebastiii if (VideoCodec != null) { DirectShowUtil.ReleaseComObject(VideoCodec, 5000); VideoCodec = null; Log.Info("BDPlayer: Cleanup VideoCodec"); } if (AudioCodec != null) { DirectShowUtil.ReleaseComObject(AudioCodec, 5000); AudioCodec = null; Log.Info("BDPlayer: Cleanup AudioCodec"); } if (_audioRendererFilter != null) { while (DirectShowUtil.ReleaseComObject(_audioRendererFilter) > 0) ; _audioRendererFilter = null; Log.Info("BDPlayer: Cleanup AudioRenderer"); } //Test to ReleaseComObject from PostProcessFilter list objects. if (PostProcessFilterVideo.Count > 0) { foreach (var ppFilter in PostProcessFilterVideo) { if (ppFilter.Value != null) DirectShowUtil.ReleaseComObject(ppFilter.Value, 5000); } PostProcessFilterVideo.Clear(); Log.Info("BDPlayer: Cleanup PostProcessVideo"); } //Test to ReleaseComObject from PostProcessFilter list objects. if (PostProcessFilterAudio.Count > 0) { foreach (var ppFilter in PostProcessFilterAudio) { if (ppFilter.Value != null) DirectShowUtil.ReleaseComObject(ppFilter.Value, 5000); } PostProcessFilterAudio.Clear(); Log.Info("BDPlayer: Cleanup PostProcessAudio"); } #endregion if (_interfaceBDReader != null) { DirectShowUtil.ReleaseComObject(_interfaceBDReader, 5000); _interfaceBDReader = null; } if (_graphBuilder != null) { DirectShowUtil.RemoveFilters(_graphBuilder); if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } while ((hr = DirectShowUtil.ReleaseComObject(_graphBuilder)) > 0) ; _graphBuilder = null; } if (_dvbSubRenderer != null) { _dvbSubRenderer.SetPlayer(null); _dvbSubRenderer = null; } if (_vmr9 != null) { _vmr9.SafeDispose(); _vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; } catch (Exception ex) { Log.Error("BDPlayer: Exception while cleaning DShow graph - {0} {1}", ex.Message, ex.StackTrace); } //switch back to directx windowed mode ExclusiveMode(false); }