protected virtual void DoStopInternal(object state) { try { //ResetVolumeLevels(); #if HAVE_SAMPLES ReleaseAudioSampleGrabber(); #endif if (mediaControl != null) { mediaControl.Stop(); mediaControl = null; mediaPosition = null; videoWindow = null; basicVideo = null; basicAudio = null; mediaEvent = null; } GC.Collect(); } catch (Exception ex) { // This is running on other thread than the DSRenderer, // so its exceptions are not caught in MediaRenderer Logger.LogException(ex); } }
/// <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; }
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; } }
void InitDirectShow(IntPtr handle) { graphBuilder = (IGraphBuilder) new FilterGraph(); mediaControl = (IMediaControl)(IVideoWindow)graphBuilder; videoWindow = (IVideoWindow)(IMediaControl)graphBuilder; mediaEventEx = (IMediaEventEx)graphBuilder; captureGraphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); outputRenderer = (IBaseFilter) new VideoMixingRenderer9(); if (outputRenderer != null) { graphBuilder.AddFilter(outputRenderer, "Output"); aspectRatioControl = outputRenderer as IVMRAspectRatioControl; aspectRatioControl9 = outputRenderer as IVMRAspectRatioControl9; } var hr = mediaEventEx.SetNotifyWindow(handle, WM_GRAPHNOTIFY, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); hr = captureGraphBuilder.SetFiltergraph(graphBuilder); DsError.ThrowExceptionForHR(hr); graphBuilderRotEntry = new DsROTEntry(graphBuilder); }
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; }
IDvdGraphBuilder GetDvdGraph() { int hr; DvdGraphBuilder dgb = null; IGraphBuilder gb = null; AMDvdRenderStatus drs; IDvdGraphBuilder idgb = null; // Get a dvd graph object dgb = new DvdGraphBuilder(); Debug.Assert(dgb != null, "new DvdGraphBuilder"); // Get the IDvdGraphBuilder interface idgb = dgb as IDvdGraphBuilder; hr = idgb.RenderDvdVideoVolume(MyDisk, AMDvdGraphFlags.HWDecPrefer, out drs); DsError.ThrowExceptionForHR(hr); // If there is no dvd in the player, you get hr == S_FALSE (1) Debug.Assert(hr == 0, "Can't find dvd"); // Get an IFilterGraph interface hr = idgb.GetFiltergraph(out gb); DsError.ThrowExceptionForHR(hr); Debug.Assert(gb != null, "GetFiltergraph"); m_ROT = new DsROTEntry(gb); m_imc = gb as IMediaControl; m_mediaEvent = gb as IMediaEventEx; return(idgb); }
private void _eventTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { _eventTimer.Enabled = false; IMediaEventEx mediaEvent = _graphBuilder as IMediaEventEx; if (mediaEvent == null) { AppLogger.Message("couldn't get IMediaEventEx from graph builder!"); return; } EventCode eventCode; IntPtr lparam1, lparam2; while (mediaEvent.GetEvent(out eventCode, out lparam1, out lparam2, 10) == 0) { AppLogger.Message("ASFNetSink -- Got Media Event: " + eventCode.ToString() + " 0x" + lparam1.ToString("X") + " 0x" + lparam2.ToString("X")); OnDirectShowEvent(eventCode, lparam1, lparam2); mediaEvent.FreeEventParams(eventCode, lparam1, lparam2); } _eventTimer.Enabled = true; } catch (Exception ex) { AppLogger.Message("ASFNetSink -- Can't get Media Event due to an error"); AppLogger.Dump(ex); } }
protected override void WndProc(ref Message m) { switch (m.Msg) { case WM_PAINT: { UpdateEnvironment(); RenderEnvironment(); NativeMethods.InvalidateRect(this.Handle, IntPtr.Zero, 0); return; } case WM_GRAPHNOTIFY: { IMediaEventEx eventEx = (IMediaEventEx)graphBuilder; EventCode evCode; IntPtr param1, param2; while (eventEx.GetEvent(out evCode, out param1, out param2, 0) == 0) { eventEx.FreeEventParams(evCode, param1, param2); Debug.WriteLine(string.Format("### Event : {0} Param1 : {1} Param2 {2}", evCode.ToString(), param1.ToString(), param2.ToString())); } break; } } base.WndProc(ref m); }
public void SetMediaItem(IResourceLocator locator, string mediaItemTitle) { // free previous opened resource FilterGraphTools.TryDispose(ref _resourceAccessor); FilterGraphTools.TryDispose(ref _rot); _state = PlayerState.Active; _isPaused = true; try { _resourceLocator = locator; _mediaItemTitle = mediaItemTitle; _resourceAccessor = _resourceLocator.CreateAccessor(); // Create a DirectShow FilterGraph CreateGraphBuilder(); // Add it in ROT (Running Object Table) for debug purpose, it allows to view the Graph from outside (i.e. graphedit) _rot = new DsROTEntry(_graphBuilder); // Add a notification handler (see WndProc) _instancePtr = Marshal.AllocCoTaskMem(4); IMediaEventEx mee = _graphBuilder as IMediaEventEx; if (mee != null) { mee.SetNotifyWindow(SkinContext.Form.Handle, WM_GRAPHNOTIFY, _instancePtr); } // Create the Allocator / Presenter object AddPresenter(); ServiceRegistration.Get <ILogger>().Debug("{0}: Adding audio renderer", PlayerTitle); AddAudioRenderer(); ServiceRegistration.Get <ILogger>().Debug("{0}: Adding preferred codecs", PlayerTitle); AddPreferredCodecs(); ServiceRegistration.Get <ILogger>().Debug("{0}: Adding source filter", PlayerTitle); AddSourceFilter(); ServiceRegistration.Get <ILogger>().Debug("{0}: Run graph", PlayerTitle); //This needs to be done here before we check if the evr pins are connected //since this method gives players the chance to render the last bits of the graph OnBeforeGraphRunning(); // Now run the graph, i.e. the DVD player needs a running graph before getting informations from dvd filter. IMediaControl mc = (IMediaControl)_graphBuilder; int hr = mc.Run(); new HRESULT(hr).Throw(); _initialized = true; OnGraphRunning(); } catch (Exception) { Shutdown(); throw; } }
void BuildGraph() { int hr; IGraphBuilder graphBuilder = new FilterGraph() as IGraphBuilder; m_ROT = new DsROTEntry(graphBuilder); IFilterGraph2 ifg2 = graphBuilder as IFilterGraph2; hr = graphBuilder.RenderFile("foo.avi", null); DsError.ThrowExceptionForHR(hr); // Get a ICaptureGraphBuilder2 ICaptureGraphBuilder2 icgb = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); hr = icgb.SetFiltergraph((IGraphBuilder)graphBuilder); DsError.ThrowExceptionForHR(hr); m_mediaEventEx = graphBuilder as IMediaEventEx; hr = m_mediaEventEx.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); Thread.Sleep(500); m_imc = graphBuilder as IMediaControl; hr = m_imc.Run(); DsError.ThrowExceptionForHR(hr); }
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); } }
/// <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> /// Build the graph to play the file /// </summary> private void BuildGraph() { // get the interfaces needed this._graphBuilder = (IGraphBuilder) new FilterGraph(); this._mediaControl = (IMediaControl)this._graphBuilder; this._mediaEvent = (IMediaEventEx)this._graphBuilder; this._mediaPosition = (IMediaPosition)this._graphBuilder; // use Intelligent Connect for the rest this._graphBuilder.RenderFile(this.FileName, null); // and the window this._vidWindow = (IVideoWindow)this._graphBuilder; this._vidWindow.put_Owner((IntPtr)this.Handle); this._vidWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); Rectangle rc = this.vidOwner.ClientRectangle; this._vidWindow.SetWindowPosition(0, 0, rc.Right, rc.Bottom); double duration = 0.0; this._mediaPosition.get_Duration(out duration); this.SetupProgressBar(duration); this.EnableButtons(this._enableControls); }
/// <summary> /// Adds the DVDNavigator filter to the graph and sets the input path. /// </summary> protected override void AddSourceFilter() { ServiceRegistration.Get <ILogger>().Debug("DvdPlayer.AddSourceFilter"); _pendingCmd = true; _dvdbasefilter = (IBaseFilter) new DVDNavigator(); if (_dvdbasefilter == null) { throw new Exception("Failed to add DVD Navigator!"); } _graphBuilder.AddFilter(_dvdbasefilter, DVD_NAVIGATOR); _dvdInfo = _dvdbasefilter as IDvdInfo2; if (_dvdInfo == null) { throw new Exception("Failed to get IDvdInfo2 from DVDNavigator!"); } _dvdCtrl = _dvdbasefilter as IDvdControl2; if (_dvdCtrl == null) { throw new Exception("Failed to get IDvdControl2 from DVDNavigator!"); } if (!IsLocalFilesystemResource) { throw new IllegalCallException("The DVDPlayer can only play local file system resources"); } using (((ILocalFsResourceAccessor)_resourceAccessor).EnsureLocalFileSystemAccess()) { string path = ((ILocalFsResourceAccessor)_resourceAccessor).LocalFileSystemPath; // check if path is a drive root (like D:), otherwise append VIDEO_TS // MediaItem always contains the parent folder. Add the required VIDEO_TS subfolder. if (!String.IsNullOrEmpty(path) && !path.EndsWith(Path.VolumeSeparatorChar.ToString())) { path = Path.Combine(path, "VIDEO_TS"); } int hr = _dvdCtrl.SetDVDDirectory(path); if (hr != 0) { throw new Exception("Failed to set DVD directory!"); } } _dvdCtrl.SetOption(DvdOptionFlag.HMSFTimeCodeEvents, true); // use new HMSF timecode format _dvdCtrl.SetOption(DvdOptionFlag.ResetOnStop, false); _mediaEvt = _graphBuilder as IMediaEventEx; if (_mediaEvt != null) { IScreenControl screenControl = ServiceRegistration.Get <IScreenControl>(); _mediaEvt.SetNotifyWindow(screenControl.MainWindowHandle, WM_DVD_EVENT, _instancePtr); } SetDefaultLanguages(); }
/// <summary> /// Default Constructor /// </summary> public DSGraphEditPanel() { InitializeComponent(); int hr = 0; // create filter graph _graph = (IFilterGraph) new FilterGraph(); _filterGraphCreated = true; // give the filter graph to the DaggerUIGraph dsDaggerUIGraph1._Graph = _graph; // mark it as having been created internally dsDaggerUIGraph1._filterGraphCreated = true; #if DEBUG rot = new DsROTEntry(_graph); #endif // Initialize items common to all constructors Init(); // get the state _mediaControl.GetState(100, out _mediaState); // Have the graph signal event via window callbacks for performance _mediaEventEx = _graph as IMediaEventEx; if (_mediaEventEx != null) { hr = _mediaEventEx.SetNotifyWindow(this.Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); } }
/// <summary> /// Used to bind the directshow graph to a message loop for notifications /// </summary> /// <param name="control">control to bind to</param> /// <param name="msg">message to listen to</param> public void SetNotifyWindow(Control control, int msg) { IMediaEventEx mediaEvent = (IMediaEventEx)_graphBuilder; int hr = mediaEvent.SetNotifyWindow(control.Handle, msg, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); }
/// <summary> /// Called by the owning HWND when an event the graph cares about occurs /// </summary> public void NotifyMediaEvent() { IMediaEventEx mediaEvent = (IMediaEventEx)_graphBuilder; if (mediaEvent != null) { bool fireComplete = false; EventCode eventCode; IntPtr param1; IntPtr param2; while (mediaEvent.GetEvent(out eventCode, out param1, out param2, 0) >= 0) { if (eventCode == EventCode.Complete) { fireComplete = true; } Log(String.Format("IMediaEventEx.GetEvent got {0}", eventCode.ToString())); mediaEvent.FreeEventParams(eventCode, param1, param2); if (fireComplete && Complete != null) { Complete(this, new EventArgs()); break; } } } }
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; }
/// <summary> /// Called by the owning HWND when an event the graph cares about occurs /// </summary> public void NotifyMediaEvent() { IMediaEventEx mediaEvent = (IMediaEventEx)_graphBuilder; if (mediaEvent != null) { bool fireComplete = false; EventCode eventCode; IntPtr param1; IntPtr param2; int hr = mediaEvent.GetEvent(out eventCode, out param1, out param2, -1); if (hr == 0) { if (eventCode == EventCode.Complete) { fireComplete = true; } mediaEvent.FreeEventParams(eventCode, param1, param2); } Debug.WriteLine("GetEvent got " + eventCode.ToString()); if (fireComplete && Complete != null) { Complete(this, new EventArgs()); } } }
// Starts playing a new cinematic public void PlayCinematic(string file, int x, int y, int w, int h) { // Lame bugfix: DirectShow and Fullscreen doesnt like eachother if (CVars.Instance.Get("r_fs", "0", CVarFlags.ARCHIVE).Integer == 1) { if (AlterGameState) { playing = true; StopCinematic(); } return; } // Check if file exists if (FileCache.Instance.Contains(file)) file = FileCache.Instance.GetFile(file).FullName; else { if (AlterGameState) { playing = true; StopCinematic(); } Common.Instance.WriteLine("PlayCinematic: Could not find video: {0}", file); return; } // Have the graph builder construct its the appropriate graph automatically this.graphBuilder = (IGraphBuilder)new FilterGraph(); int hr = graphBuilder.RenderFile(file, null); DsError.ThrowExceptionForHR(hr); mediaControl = (IMediaControl)this.graphBuilder; mediaEventEx = (IMediaEventEx)this.graphBuilder; videoWindow = this.graphBuilder as IVideoWindow; basicVideo = this.graphBuilder as IBasicVideo; // Setup the video window hr = this.videoWindow.put_Owner(Renderer.Instance.form.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); // Set the video size //int lWidth, lHeight; //hr = this.basicVideo.GetVideoSize(out lWidth, out lHeight); hr = this.videoWindow.SetWindowPosition(x, y, w, h); videoWindow.put_FullScreenMode((CVars.Instance.Get("r_fs", "0", CVarFlags.ARCHIVE).Integer == 1) ? OABool.True : OABool.False); DsError.ThrowExceptionForHR(hr); // Run the graph to play the media file hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); playing = true; if (AlterGameState) Client.Instance.state = CubeHags.common.ConnectState.CINEMATIC; Common.Instance.WriteLine("Playing cinematic: {0}", file); EventCode code; }
/// <summary> /// Creates a new IFilterGraph2 interface. /// </summary> protected virtual void CreateGraphBuilder() { _graphBuilder = (IFilterGraph2) new FilterGraph(); _mc = (IMediaControl)_graphBuilder; _me = (IMediaEventEx)_graphBuilder; _ms = (IMediaSeeking)_graphBuilder; }
private void Cleanup(bool stop) { if (this.fmc != null && stop) { this.fmc.Stop(); } if (this.ime != null) { this.ime.SetNotifyWindow(0, WM_GRAPHNOTIFY, 0); this.ime = null; } if (this.ivw != null) { this.ivw.Owner = 0; this.ivw = null; } if (this.isg != null) { Marshal.ReleaseComObject(this.isg); } if (this.fmc != null) { Marshal.ReleaseComObject(this.fmc); } if (this.iamsc != null) { Marshal.ReleaseComObject(this.iamsc); } if (this.icgb != null) { Marshal.ReleaseComObject(this.icgb); } }
private bool PlayVideo(string path) { CleanUp(); FilterGraph = new FilgraphManager(); FilterGraph.RenderFile(path); BasicAudio = FilterGraph as IBasicAudio; try { VideoWindow = FilterGraph as IVideoWindow; VideoWindow.Owner = (int)panel1.Handle; VideoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN; VideoWindow.SetWindowPosition(panel1.ClientRectangle.Left, panel1.ClientRectangle.Top, panel1.ClientRectangle.Width, panel1.ClientRectangle.Height); } catch (Exception) { VideoWindow = null; return(false); } MediaEvent = FilterGraph as IMediaEvent; MediaEventEx = FilterGraph as IMediaEventEx; MediaPosition = FilterGraph as IMediaPosition; MediaControl = FilterGraph as IMediaControl; MediaControl.Run(); return(true); }
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(); }
public void Run() { if (!string.IsNullOrWhiteSpace(this.Source)) { if (this.State == MediaStatus.Stopped) { try { filterGraph = new FilgraphManager(); this.filterGraph.RenderFile(this.Source); basicAudio = filterGraph as IBasicAudio; try { videoWindow = filterGraph as IVideoWindow; videoWindow.Owner = (int)this.Handle; videoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN; videoWindow.SetWindowPosition(this.ClientRectangle.Left, this.ClientRectangle.Top, this.ClientRectangle.Width, this.ClientRectangle.Height); } catch (Exception) { videoWindow = null; } mediaEvent = filterGraph as IMediaEvent; mediaEventEx = filterGraph as IMediaEventEx; mediaEventEx.SetNotifyWindow((int)base.Handle, WM_GRAPHNOTIFY, 0); mediaPosition = filterGraph as IMediaPosition; mediaControl = filterGraph as IMediaControl; } catch { try { mediaControl.StopWhenReady(); } catch { mediaControl.Stop(); } this.CleanUp(); this.State = MediaStatus.Stopped; throw; } } if (this.State != MediaStatus.Running) { this.mediaControl.Run(); this.State = MediaStatus.Running; } } }
public int AddClip(string path, out ClipEntry pClip) { int it = m_Clips.Count; pClip = new ClipEntry(); m_Clips.Add(pClip); int hr = pClip.Create(m_pController, path); // if we expect both audio and video, then all clips // must have both audio and video. // If the first clip is video only, then switch // to video-only automatically if ((hr == VFW_E_UNSUPPORTED_AUDIO) && (m_Clips.Count == 1)) { // new controller, different options (only one video stream) if (m_pController != null) { Marshal.ReleaseComObject(m_pController); m_pController = null; } m_pController = new GMFBridgeController() as IGMFBridgeController; m_pController.SetNotify(m_hwndApp, m_msgSegment); m_pController.AddStream(true, eFormatType.Uncompressed, false); m_pController.SetBufferMinimum(200); // try again hr = pClip.Create(m_pController, path); } if (hr >= 0) { pClip.SetStartPosition(m_tDuration); m_tDuration += pClip.Duration(); // if this is the first clip, create the render graph if (m_Clips.Count == 1) { m_pRenderGraph = new FilterGraph() as IGraphBuilder; hr = m_pController.CreateRenderGraph(pClip.SinkFilter(), m_pRenderGraph, out m_pRenderGraphSourceFilter); if (hr >= 0 && m_hwndApp != IntPtr.Zero) { IMediaEventEx pME = m_pRenderGraph as IMediaEventEx; if (pME != null) { pME.SetNotifyWindow(m_hwndApp, m_msgEvent, IntPtr.Zero); } } } } else { pClip.Dispose(); m_Clips.RemoveAt(it); } return(hr); }
public override void OnVideoEvent(int cookies) { if (this.graphBuilder == null || this.graphBuilder2 == null) { return; } try { if (cookies == cookiesSink) { IMediaEventEx mediaEvent = this.graphBuilder as IMediaEventEx; EventCode eventCode; IntPtr param1, param2; while (mediaEvent.GetEvent(out eventCode, out param1, out param2, 0) >= 0) { Trace.WriteLineIf(trace.TraceVerbose, "OnVideoEvent(Sink) -> " + eventCode.ToString()); if (eventCode == EventCode.VMRRenderDeviceSet) { VideoRefresh(); } //switch (eventCode) //{ // // Call application-defined functions for each // // type of event that you want to handle. //} int hr = mediaEvent.FreeEventParams(eventCode, param1, param2); } } else if (cookies == cookiesSource) { IMediaEventEx mediaEvent = this.graphBuilder2 as IMediaEventEx; EventCode eventCode; IntPtr param1, param2; while (mediaEvent.GetEvent(out eventCode, out param1, out param2, 0) >= 0) { Trace.WriteLineIf(trace.TraceVerbose, "OnVideoEvent(Source) -> " + eventCode.ToString()); if (eventCode == EventCode.VMRRenderDeviceSet) { VideoRefresh(); } //switch (eventCode) //{ // // Call application-defined functions for each // // type of event that you want to handle. //} int hr = mediaEvent.FreeEventParams(eventCode, param1, param2); } } } catch (Exception ex) { Trace.WriteLineIf(trace.TraceError, ex.ToString()); } }
/// <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); } }
private void InitGraph() { FilterGraph = new FilterGraph(); this.GraphBuilder = (IGraphBuilder)FilterGraph; this.MediaControl = (IMediaControl)this.GraphBuilder; this.VideoWindow = (IVideoWindow)this.GraphBuilder; this.MediaEventEx = (IMediaEventEx)this.GraphBuilder; }
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(); }
/// <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 void CloseInterfaces() { if (mediaEvent != null) { hresult = mediaControl.Stop(); Marshal.ThrowExceptionForHR(hresult); } mediaControl = null; mediaEvent = null; graphBuilder = null; if (filterGraph != null) Marshal.ReleaseComObject(filterGraph); filterGraph = null; }
public CaptureForm() { InitializeComponent(); graph_builder = (IGraphBuilder)new FilterGraph(); media_control = (IMediaControl)graph_builder; events = (IMediaEventEx)graph_builder; grabber = (ISampleGrabber)new SampleGrabber(); AMMediaType media_type = new AMMediaType(); media_type.majorType = MediaType.Video; media_type.subType = MediaSubType.RGB24; grabber.SetMediaType( media_type ); grabber.SetCallback( this, 1 ); cbDevices.Items.AddRange( GetDevices( FilterCategory.VideoInputDevice ) ); }
// 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); }
//Метод CleanUp (Зачистка графов) public void CleanUp() { if (mediaControl != null) mediaControl.Stop(); CurrentStatus = mStatus.Stop; if (videoWindow != null) { videoWindow.put_Visible(0); videoWindow.put_Owner(new IntPtr(0)); } if (mediaControl != null) mediaControl = null; if (mediaPosition != null) mediaPosition = null; if (mediaEventEx != null) mediaEventEx = null; if (mediaEvent != null) mediaEvent = null; if (videoWindow != null) videoWindow = null; if (basicAudio != null) basicAudio = null; if (graphBuilder != null) graphBuilder = null; }
/// <summary> /// Plays the given mediafile in the internal mediaplayer /// </summary> /// <param name="FilePath">File to play</param> public void ShowMedia(string FilePath) { StopMedia(); Lbl_CurrentMedia.Text = Path.GetFileName(FilePath); m_objFilterGraph = new FilgraphManager(); m_objFilterGraph.RenderFile(FilePath); m_objBasicAudio = m_objFilterGraph as IBasicAudio; try { m_objVideoWindow = m_objFilterGraph as IVideoWindow; m_objVideoWindow.Owner = (int)panel2.Handle; //m_objVideoWindow.Owner = (int)panel1.Handle; m_objVideoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN; m_objVideoWindow.SetWindowPosition(panel2.ClientRectangle.Left, panel2.ClientRectangle.Top, panel2.ClientRectangle.Width, panel2.ClientRectangle.Height); } catch (Exception ex) { Console.WriteLine(ex); m_objVideoWindow = null; } m_objMediaEvent = m_objFilterGraph as IMediaEvent; m_objMediaEventEx = m_objFilterGraph as IMediaEventEx; m_objMediaEventEx.SetNotifyWindow((int)this.Handle, WM_GRAPHNOTIFY, 0); m_objMediaPosition = m_objFilterGraph as IMediaPosition; m_objMediaControl = m_objFilterGraph as IMediaControl; m_objMediaControl.Run(); m_CurrentStatus = MediaStatus.Running; UpdateMediaButtons(); //UpdateStatusBar(); //UpdateToolBar(); }
/** * 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; }
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 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> /// Sets the MediaEventEx interface /// </summary> private void SetMediaEventExInterface(IMediaEventEx mediaEventEx) { m_mediaEvent = mediaEventEx; m_mediaEvent.SetNotifyWindow(HwndHelper.Handle, WM_GRAPH_NOTIFY, (IntPtr)GraphInstanceId); }
/// <summary> /// Resets the local graph resources to their /// default settings /// </summary> private void ResetLocalGraphResources() { m_basicAudio = null; m_mediaControl = null; m_mediaEvent = null; }
/// <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); }
public void CloseInterfaces() { // Stop previewing data if (this.mediaControl != null) this.mediaControl.StopWhenReady(); this.currentState = PlayState.Stopped; // Stop receiving events if (this.mediaEventEx != null) this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); // Relinquish ownership (IMPORTANT!) of the video window. // Failing to call put_Owner can lead to assert failures within // the video renderer, as it still assumes that it has a valid // parent window. if(this.videoWindow != null) { this.videoWindow.put_Visible(OABool.False); this.videoWindow.put_Owner(IntPtr.Zero); } // Remove filter graph from the running object table if (rot != null) { rot.Dispose(); rot = null; } // Release DirectShow interfaces Marshal.ReleaseComObject(this.mediaControl); this.mediaControl = null; Marshal.ReleaseComObject(this.mediaEventEx); this.mediaEventEx = null; Marshal.ReleaseComObject(this.videoWindow); this.videoWindow = null; Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null; Marshal.ReleaseComObject(this.captureGraphBuilder); this.captureGraphBuilder = null; }
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; }
private void Cleanup(bool stop) { if (this.fmc != null && stop) { this.fmc.Stop(); } if (this.ime != null) { this.ime.SetNotifyWindow(0, WM_GRAPHNOTIFY, 0); this.ime = null; } if (this.ivw != null) { this.ivw.Owner = 0; this.ivw = null; } if (this.isg != null) Marshal.ReleaseComObject(this.isg); if (this.fmc != null) Marshal.ReleaseComObject(this.fmc); if (this.iamsc != null) Marshal.ReleaseComObject(this.iamsc); if (this.icgb != null) Marshal.ReleaseComObject(this.icgb); }
private void 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> 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> 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); } }
/* // Uncomment this version of FindCaptureDevice to use the DsDevice helper class // (and comment the first version of course) public IBaseFilter FindCaptureDevice() { System.Collections.ArrayList devices; object source; // Get all video input devices devices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); // Take the first device DsDevice device = (DsDevice)devices[0]; // Bind Moniker to a filter object Guid iid = typeof(IBaseFilter).GUID; device.Mon.BindToObject(null, null, ref iid, out source); // An exception is thrown if cast fail return (IBaseFilter) source; } */ public void GetInterfaces() { int hr = 0; // An exception is thrown if cast fail this.graphBuilder = (IGraphBuilder) new FilterGraph(); this.captureGraphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); this.mediaControl = (IMediaControl) this.graphBuilder; this.videoWindow = (IVideoWindow) this.graphBuilder; this.mediaEventEx = (IMediaEventEx) this.graphBuilder; hr = this.mediaEventEx.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); }
private void InitInterfaces() { try { // initialise the graph and get the graph builder and media control from it _graph = new FilterGraph(); _mediaEvent = (IMediaEventEx)_graph; _graphBuilder = (IGraphBuilder)_graph; _mediaControl = (IMediaControl)_graph; } catch (Exception ex) { throw new ApplicationException("Couldn't initialise filter graph: " + ex.Message); } }
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 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; } }
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 Run() { if (this.fmc == null) return; IGraphBuilder igb = (IGraphBuilder)this.fmc; try { // tell the graph builder about the filter graph this.icgb.SetFiltergraph(igb); igb.AddFilter(this.sf, "Video Capture"); igb.AddFilter(this.sgf, "Sample Grabber"); this.icgb.RenderStream(ref PIN_CATEGORY_CAPTURE, ref MEDIATYPE_Video, this.sf, this.sgf, null); // access different interfaces, ask runtime to notify this window this.ime = (IMediaEventEx)this.fmc; this.ime.SetNotifyWindow((int)this.Handle, WM_GRAPHNOTIFY, 0); // sets the video owner and style of this window this.ivw = (IVideoWindow)this.fmc; this.ivw.Owner = (int)this.Handle; this.ivw.WindowStyle = WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; ivw.SetWindowPosition(this.ClientRectangle.Left, this.ClientRectangle.Top, this.ClientRectangle.Width, this.ClientSize.Height - this.btnCapture.Height - vertical_space); // get the ball rolling this.fmc.Run(); } catch (Exception ex) { Cleanup(false); MessageBox.Show("Couldn't run: " + ex.Message); } }
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 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 button1_Click(object sender, System.EventArgs e) { if (System.IO.File.Exists(textBox1.Text)) { Cursor.Current = Cursors.WaitCursor; button1.Enabled = false; if (cam != null) { cam.Dispose(); cam = null; } if (cam == null) { cam = new Capture(textBox1.Text, textBox2.Text, panel1); mediaEvent = cam.MediaEventEx; int hr = mediaEvent.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero); cam.Start(); } } }
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); } }