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); } }
protected void CheckAudio() { int volume = _isMuted ? 0 : _volume; IBasicAudio audio = _graphBuilder as IBasicAudio; if (audio != null) { // Our volume range is from 0 to 100, IBasicAudio volume range is from -10000 to 0 (in hundredth decibel). // See http://msdn.microsoft.com/en-us/library/dd389538(VS.85).aspx (IBasicAudio::put_Volume method) audio.put_Volume(VolumeToHundredthDeciBel(volume)); } }
void DSGraphEditPanel_Disposed(object sender, EventArgs e) { // only stop the graph if we created it if (_filterGraphCreated) { Stop(); } timeSliderTimer.Enabled = false; // remove from rot table if we added it if (rot != null) { rot.Dispose(); rot = null; } try { // nix the media sink if (_mediaEventEx != null) { _mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); } _graphBuilder = null; _mediaControl = null; _mediaSeeking = null; _basicAudio = null; _basicVideo = null; _videoWindow = null; _mediaEventEx = null; // only release the filtergraph if WE created it. If the user passed one into a constructor, // it's up to them to release it. if (_filterGraphCreated) { int refc = Marshal.ReleaseComObject(_graph); } // if it is a connected graph, renounce all claim on the proxie's RCW if (_isRemoteGraph) { Marshal.FinalReleaseComObject(_graph); } } catch (InvalidComObjectException ex) { // the RCW became disconnected, This is most likely caused by connecting to a remote graph // in the same AppDomain. Just ignore it. } }
public void OpenFile(string filename) { // Check filename if (filename == string.Empty) { throw new ArgumentNullException(); } // Check file exists if (File.Exists(filename)) { this.MediaFile = filename; } else { throw new ArgumentException("File does not exist"); } int hr = 0; // Create graph this.graphBuilder = (IGraphBuilder) new FilterGraph(); // Open file hr = this.graphBuilder.RenderFile(this.MediaFile, 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; this.basicAudio = this.graphBuilder as IBasicAudio; // Detect media type this.MediaType = DetectMediaType(); // Detect video resolution this.Resolution = DetectVideoResolution(); // Detect media duration int seconds = DetectMediaLength(); this.Length = new TimeSpan(0, 0, 0, seconds, 0); //AspectRatio(1); ScaleVideoFit(); this.PlaybackStatus = PlayState.Open; }
/// <summary> /// The dispose. /// </summary> public override void Dispose() { this.ReleaseEventThread(); //// Release and zero DirectShow interfaces if (this.mediaSeeking != null) { this.mediaSeeking = null; } if (this.mediaPosition != null) { this.mediaPosition = null; } if (this.mediaControl != null) { this.mediaControl = null; } if (this.basicAudio != null) { this.basicAudio = null; } if (this.basicVideo != null) { this.basicVideo = null; } if (this.mediaEvent != null) { this.mediaEvent = null; } if (this.videoWindow != null) { this.videoWindow = null; } if (this.frameStep != null) { this.frameStep = null; } // Release DirectShow interfaces base.Dispose(); // Clear file name to allow selection of new file with open dialog this.VideoFilename = string.Empty; }
private static void Connect_up(int dInput, int dOutput) { object source = null, inputD = null; DsDevice[] devices; devices = DsDevice.GetDevicesOfCat(FilterCategory.AudioRendererCategory); DsDevice device = devices[dOutput]; Guid iid = typeof(IBaseFilter).GUID; device.Mon.BindToObject(null, null, ref iid, out source); m_objFilterGraph = (IGraphBuilder) new FilterGraph(); m_objFilterGraph.AddFilter((IBaseFilter)source, "Audio Input pin (rendered)"); devices = DsDevice.GetDevicesOfCat(FilterCategory.AudioInputDevice); device = devices[dInput]; // iid change? device.Mon.BindToObject(null, null, ref iid, out inputD); m_objFilterGraph.AddFilter((IBaseFilter)inputD, "Capture"); int result; IEnumPins pInputPin = null, pOutputPin = null; // Pin enumeration IPin pIn = null, pOut = null; // Pins try { IBaseFilter newI = (IBaseFilter)inputD; result = newI.EnumPins(out pInputPin);// Enumerate the pin if (result.Equals(0)) { // Get hold of the pin as seen in GraphEdit newI.FindPin("Capture", out pIn); } IBaseFilter ibfO = (IBaseFilter)source; ibfO.EnumPins(out pOutputPin);//Enumerate the pin ibfO.FindPin("Audio Input pin (rendered)", out pOut); try { pIn.Connect(pOut, null); // Connect the input pin to output pin } catch (Exception ex) { Console.WriteLine(ex.Message); } } catch (Exception ex) { Console.WriteLine(ex.Message); } m_objBasicAudio = m_objFilterGraph as IBasicAudio; m_objMediaControl = m_objFilterGraph as IMediaControl; }
protected virtual void SetPlayerCollaborators() { basicAudio = filgraphManager as IBasicAudio; mediaPosition = filgraphManager as IMediaPosition; mediaControl = filgraphManager as IMediaControl; mediaEvent = filgraphManager as IMediaEvent; mediaEventEx = filgraphManager as IMediaEventEx; messageHandler.MediaEventEx = mediaEventEx; }
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; } }
/// <summary>Clean up the video resources</summary> private void CloseInterfaces() { Stop(); AttachToWindow(IntPtr.Zero); PlayState = EPlayState.Cleanup; lock (m_shutdown_lock) m_shutdown = true; if (m_event != null) { m_event.Set(); // Release the thread } m_event = null; // Wait for the thread to end if (m_media_event_thread != null) { m_media_event_thread.Join(); } m_media_event_thread = null; if (m_samp_grabber != null) { Marshal.ReleaseComObject(m_samp_grabber); } m_media_ctrl = null; m_media_position = null; m_samp_grabber = null; m_video_window = null; m_basic_video = null; m_basic_audio = null; #if DEBUG if (m_ds_rot != null) { m_ds_rot.Dispose(); } m_ds_rot = null; #endif if (m_filter_graph != null) { Marshal.ReleaseComObject(m_filter_graph); } m_filter_graph = null; GC.Collect(); GC.WaitForPendingFinalizers(); }
private bool BuildSoundRenderer(IGraphBuilder pGraphBuilder) { var result = false; var renderer = pGraphBuilder.AddSoundRenderer(); if (renderer != null) { _directSoundBaseFilter = renderer.Item1; _basicAudio = renderer.Item2; result = true; } return(result); }
private void SetVolume(int _volume) { if (m_BasicAudio == null) { if (m_GraphBuilder == null) { return; } else { m_BasicAudio = (IBasicAudio)m_GraphBuilder; } } m_BasicAudio.put_Volume(_volume); }
private void menuItem2_Click(object sender, System.EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*"; if (DialogResult.OK == openFileDialog.ShowDialog()) { CleanUp(); m_objFilterGraph = new FilgraphManager(); m_objFilterGraph.RenderFile(openFileDialog.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 = "DirectShow - [" + openFileDialog.FileName + "]"; m_objMediaControl.Run(); m_CurrentStatus = MediaStatus.Running; UpdateStatusBar(); UpdateToolBar(); } }
/// <summary> /// Initialize items common to all constructors /// </summary> private void Init() { // get interfaces _mediaControl = _graph as IMediaControl; _basicAudio = _graph as IBasicAudio; _basicVideo = _graph as IBasicVideo2; _graphBuilder = _graph as IGraphBuilder; // hook the DaggerGraph events dsDaggerUIGraph1.Graph.BeforeNodeRemoved += new BeforeNodeRemoveHandler(Graph_BeforeNodeRemoved); dsDaggerUIGraph1.Graph.BeforePinsConnected += new PinBeforeConnectedHandler(Graph_BeforePinsConnected); dsDaggerUIGraph1.Graph.BeforePinsDisconnected += new PinBeforeDisconnectedHandler(Graph_BeforePinsDisconnected); dsDaggerUIGraph1.BeforeSelectionDeleted += new BeforeDeleteSelected(dsDaggerUIGraph1_BeforeSelectionDeleted); dsDaggerUIGraph1.Graph.OnTopologyChanged += new EventHandler(Graph_OnTopologyChanged); this.Disposed += new EventHandler(DSGraphEditPanel_Disposed); }
//setzt alle DirectShow Sachen auf null private void CleanUp() { if (MediaControl != null) { MediaControl.Stop(); } if (MediaEventEx != null) { MediaEventEx.SetNotifyWindow(0, 0, 0); } if (VideoWindow != null) { VideoWindow.Visible = 0; VideoWindow.Owner = 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 (FilterGraph != null) { FilterGraph = null; } }
internal void trackBarBalance_ValueChanged(object sender, EventArgs e) { MainForm.Settings.Balance = this.trackBarBalance.Value; if (this.MainForm.GraphBuilder != null) { IBasicAudio basicAudio = this.MainForm.GraphBuilder.FilterGraph as IBasicAudio; if (basicAudio != null) { basicAudio.put_Balance(this.trackBarBalance.Value); int balance = 0; basicAudio.get_Balance(out balance); this.labelBalanceLevel.Text = balance.ToString(); return; } } this.labelBalanceLevel.Text = this.trackBarBalance.Value.ToString(); }
private void init(string s) //³õʼ²¥·ÅÆ÷ { try { m_objFilterGraph = new FilgraphManager(); m_objFilterGraph.RenderFile(s); m_objBasicAudio = m_objFilterGraph as IBasicAudio; m_objMediaEvent = m_objFilterGraph as IMediaEvent; m_objMediaEventEx = m_objFilterGraph as IMediaEventEx; m_objMediaControl = m_objFilterGraph as IMediaControl; } catch {} }
//TODO Fichier déjà utilisé.... surement par Quartz. Essayer de libérer les ressources de la librairie public void Play(Guid id, byte[] file) { objFilterGraph = new FilgraphManager(); audio = (IBasicAudio) objFilterGraph; //pb d'accès concurrenciel string path = ConfigurationManager.AppSettings["MediaCache"] + id + ".mp3"; File.WriteAllBytes(path, file); objFilterGraph.RenderFile(path); objMediaPosition = objFilterGraph as IMediaPosition; objFilterGraph.Run(); tmProgressionFlux = new Timer(1000) { Enabled = true }; tmProgressionFlux.Elapsed += TmProgressionFluxTick; TimerResume(); }
/// <summary> create the used COM components and get the interfaces. </summary> private bool GetInterfaces() { int iStage = 1; string audioDevice; using (Settings xmlreader = new MPSettings()) { audioDevice = xmlreader.GetValueAsString("audioplayer", "sounddevice", "Default DirectSound Device"); } //Type comtype = null; //object comobj = null; try { graphBuilder = (IGraphBuilder) new FilterGraph(); iStage = 5; DirectShowUtil.AddAudioRendererToGraph(graphBuilder, audioDevice, false); int hr = graphBuilder.RenderFile(m_strCurrentFile, null); 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; return(true); } catch (Exception ex) { Log.Info("Can not start {0} stage:{1} err:{2} stack:{3}", m_strCurrentFile, iStage, ex.Message, ex.StackTrace); return(false); } }
//Метод CleanUp (Зачистка графов) public void CleanUp() { if (mediaControl != null) mediaControl.Stop(); CurrentStatus = mStatus.Stop; if (videoWindow != null) { videoWindow.put_Visible(0); videoWindow.put_Owner(new IntPtr(0)); } if (mediaControl != null) mediaControl = null; if (mediaPosition != null) mediaPosition = null; if (mediaEventEx != null) mediaEventEx = null; if (mediaEvent != null) mediaEvent = null; if (videoWindow != null) videoWindow = null; if (basicAudio != null) basicAudio = null; if (graphBuilder != null) graphBuilder = null; }
// Methods internal AudioAnimate(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc) { this.m_objFilterGraph = null; this.m_objBasicAudio = null; this.m_objMediaEvent = null; this.m_objMediaEventEx = null; this.m_objMediaPosition = null; this.m_objMediaControl = null; this.fillColor = Color.Khaki; this.fileName = string.Empty; this.m_CurrentStatus = MediaStatus.None; this.timer = new Timer(); this.oldtime = 0f; this.timertime = 0f; this.timer.Interval = 100; this.timer.Tick += new EventHandler(this.TimerTick); }
public void DoTests() { try { // We need a stereo sound renderer... BuildGraph("foo.avi", out this.graphBuilder, out this.filter); this.audio = (IBasicAudio)this.filter; TestBalance(); TestVolume(); } finally { Marshal.ReleaseComObject(this.filter); Marshal.ReleaseComObject(this.graphBuilder); } }
public void SetVolume(double volume) { IBasicAudio audio = _graphBuilder as IBasicAudio; if (audio != null) { int iVolume; if (volume <= -100) { iVolume = -10000; } else { iVolume = (int)(volume * 100); } audio.put_Volume(iVolume); } }
/// <summary> /// Creation of the fgm and the adding / removing of filters needs to happen on the /// same thread. So make sure it all happens on the UI thread. /// </summary> private void _RtpStream_FirstFrameReceived() { lock (fgmLock) { DisposeFgm(); Debug.Assert(fgm == null); fgm = new FilgraphManagerClass(); IGraphBuilder iGB = (IGraphBuilder)fgm; rotID = FilterGraph.AddToRot(iGB); IBaseFilter rtpSource = RtpSourceClass.CreateInstance(); ((MSR.LST.MDShow.Filters.IRtpSource)rtpSource).Initialize(rtpStream); iGB.AddFilter(rtpSource, "RtpSource"); // Add the chosen audio renderer FilterInfo fi = SelectedSpeaker(); iGB.AddFilter(Filter.CreateBaseFilter(fi), fi.Name); iGB.Render(Filter.GetPin(rtpSource, _PinDirection.PINDIR_OUTPUT, Guid.Empty, Guid.Empty, false, 0)); iBA = (IBasicAudio)fgm; currentVolume = (int)Math.Round(Math.Pow(10.0, (2.0 * (double)(iBA.Volume + 10000)) / 10000.0)); iBA = null; uiState &= ~(int)FAudioVideo.UIState.RemoteAudioStopped; if (form != null) { ((FAudioVideo)form).UpdateAudioUI(uiState); } // FirstFrameReceived interprets fgmState as the *desired* state for the fgm // Because ResumePlayingAudio won't actually start if the state is already // Running, we change it to Stopped so that it will start if (IsPlaying && fgmState == FilterGraph.State.Running) { fgmState = FilterGraph.State.Stopped; ResumePlayingAudio(); } } }
/// <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(); }
/// <summary> /// Initialises DirectShow interfaces /// </summary> private void InitInterfaces() { var comtype = Type.GetTypeFromCLSID(Clsid.FilterGraph); if (comtype == null) { throw new NotSupportedException("DirectX (8.1 or higher) not installed?"); } var fg = Activator.CreateInstance(comtype); m_graphBuilder = (IGraphBuilder)fg; m_mediaControl = (IMediaControl)fg; m_mediaEvent = (IMediaEventEx)fg; m_mediaSeeking = (IMediaSeeking)fg; m_mediaPosition = (IMediaPosition)fg; m_basicAudio = (IBasicAudio)fg; fg = null; }
private void DisposeFgm() { lock (fgmLock) { if (fgm != null) { // We need to manually unblock the stream in case there is no data flowing if (rtpStream != null) { rtpStream.UnblockNextFrame(); } FilterGraph.RemoveFromRot(rotID); fgm.Stop(); FilterGraph.RemoveAllFilters(fgm); fgm = null; iBA = null; } } }
private void playAudioToDevice(string fName, int devIndex) { object source = null; DsDevice[] devices; devices = DsDevice.GetDevicesOfCat(FilterCategory.AudioRendererCategory); DsDevice device = (DsDevice)devices[devIndex]; Guid iid = typeof(IBaseFilter).GUID; device.Mon.BindToObject(null, null, ref iid, out source); m_objFilterGraph = (IGraphBuilder) new FilterGraph(); m_objFilterGraph.AddFilter((IBaseFilter)source, "Audio Render"); m_objFilterGraph.RenderFile(fName, ""); m_objBasicAudio = m_objFilterGraph as IBasicAudio; m_objMediaControl = m_objFilterGraph as IMediaControl; m_objMediaControl.Run(); }
private void CloseInterfaces() { try { lock (this) { if (mediaEventEx != null) { var hr = mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); } if (mediaEventEx != null) { mediaEventEx = null; } if (mediaControl != null) { mediaControl = null; } if (basicAudio != null) { basicAudio = null; } if (basicVideo != null) { basicVideo = null; } if (graphBuilder != null) { Marshal.ReleaseComObject(graphBuilder); } graphBuilder = null; GC.Collect(); } } catch { } }
public bool SetSource(string FileName) { try { FilterGraph = new FilgraphManager(); object ppUnk = null; FilterGraph.AddSourceFilter(FileName, out ppUnk); FilterGraph.RenderFile(FileName); IFilterInfo Info = (IFilterInfo)ppUnk; TestControl = Info.Filter as ITestControl; BasicAudio = FilterGraph as IBasicAudio; VideoWindow = FilterGraph as IVideoWindow; MediaControl = FilterGraph as IMediaControl; } catch (Exception ex) { Clear(); return(false); } return(true); }
/// <summary> /// Closes DirectShow interfaces /// </summary> private void CloseInterfaces() { if (m_mediaEvent != null) { m_mediaControl.Stop(); //0x00008001 = WM_GRAPHNOTIFY m_mediaEvent.SetNotifyWindow(IntPtr.Zero, 0x00008001, IntPtr.Zero); } m_mediaControl = null; m_mediaEvent = null; m_graphBuilder = null; m_mediaSeeking = null; m_mediaPosition = null; m_basicAudio = null; if (m_comObject != null) { Marshal.ReleaseComObject(m_comObject); } m_comObject = null; }
protected virtual void CloseInterfaces() { if (_mediaControl != null) { _mediaControl.Stop(); _mediaControl = null; } // CALLBACK handle if (_mediaEventEx != null) { _mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); _mediaEventEx = null; } if (_renderer != null) { try { _renderer.Close(); } catch (Exception e) { // TODO: lot it } } // GRAPH interfaces _filterGraph2 = null; _basicAudio = null; _mediaSeeking = null; if (_graphBuilder != null) { while (Marshal.ReleaseComObject(_graphBuilder) > 0) { } _graphBuilder = null; } }
private HRESULT CloseInterfaces() { try { OnCloseInterfaces(); if (m_MediaEventEx != null) { m_MediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); m_MediaEventEx = null; } if (m_VideoWindow != null) { m_VideoWindow.put_Visible(0); m_VideoWindow.put_Owner(IntPtr.Zero); m_VideoWindow = null; } m_MediaSeeking = null; m_MediaPosition = null; m_BasicVideo = null; m_BasicAudio = null; m_MediaControl = null; while (m_Filters.Count > 0) { DSFilter _filter = m_Filters[0]; m_Filters.RemoveAt(0); _filter.Dispose(); } if (m_GraphBuilder != null) { Marshal.ReleaseComObject(m_GraphBuilder); m_GraphBuilder = null; } GC.Collect(); return((HRESULT)NOERROR); } catch { return((HRESULT)E_FAIL); } }
private void open() { int hr; if (this.GraphBuilder == null) { this.GraphBuilder = (IGraphBuilder) new FilterGraph(); hr = GraphBuilder.RenderFile(file, null);//读取文件 DsError.ThrowExceptionForHR(hr); this.MediaControl = (IMediaControl)this.GraphBuilder; this.MediaEventEx = (IMediaEventEx)this.GraphBuilder; MediaSeeking = (IMediaSeeking)this.GraphBuilder; MediaSeeking.SetTimeFormat(TIME_FORMAT_FRAME); MediaSeeking.SetRate(0.3); this.VideoFrameStep = (IVideoFrameStep)this.GraphBuilder; // MediaPosition= (IMediaPosition)this.GraphBuilder; this.VideoWindow = this.GraphBuilder as IVideoWindow; this.BasicVideo = this.GraphBuilder as IBasicVideo; this.BasicAudio = this.GraphBuilder as IBasicAudio; hr = this.MediaEventEx.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); 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); long time; MediaSeeking.GetDuration(out time); label20.Text = time.ToString(); trackBar1.SetRange(0, (int)time); t = new Thread(new ThreadStart(updateTimeBarThread)); } }
/** * To clean up the FilterGraph and other Objects * */ public void CleanUp() { if (m_objMediaControl != null) m_objMediaControl.Stop(); if (m_objMediaEventEx != null) m_objMediaEventEx.SetNotifyWindow(0, 0, 0); if (m_objVideoWindow != null) { m_objVideoWindow.Visible = 0; m_objVideoWindow.Owner = 0; } if (m_objMediaControl != null) m_objMediaControl = null; if (m_objMediaPosition != null) m_objMediaPosition = null; if (m_objMediaEventEx != null) m_objMediaEventEx = null; if (m_objMediaEvent != null) m_objMediaEvent = null; if (m_objVideoWindow != null) m_objVideoWindow = null; if (m_objBasicAudio != null) m_objBasicAudio = null; if (m_objFilterGraph != null) m_objFilterGraph = null; }
/// <summary> /// Resets the local graph resources to their /// default settings /// </summary> private void ResetLocalGraphResources() { m_graph = null; if (m_basicAudio != null) { Marshal.ReleaseComObject(m_basicAudio); } m_basicAudio = null; if (m_mediaControl != null) { Marshal.ReleaseComObject(m_mediaControl); } m_mediaControl = null; if (m_mediaEvent != null) { Marshal.ReleaseComObject(m_mediaEvent); } m_mediaEvent = null; }
public bool Open(PandoraSong file) { try { Close(); graphBuilder = (IGraphBuilder) new FilterGraph(); // create interface objects for various actions mediaControl = (IMediaControl)graphBuilder; mediaEventEx = (IMediaEventEx)graphBuilder; mediaSeeking = (IMediaSeeking)graphBuilder; mediaPosition = (IMediaPosition)graphBuilder; basicAudio = (IBasicAudio)graphBuilder; int hr = 0; StartEventLoop(); //hr = graphBuilder.AddFilter( // Have the graph builder construct its the appropriate graph automatically hr = graphBuilder.RenderFile(file.AudioURL, null); DsError.ThrowExceptionForHR(hr); // maintain previous volume level so it persists from track to track if (PreviousVolume != null) { Volume = (double)PreviousVolume; } loadedSong = file; return(true); } catch (Exception) { return(false); } }
/// <summary> /// Resets the local graph resources to their /// default settings /// </summary> private void ResetLocalGraphResources() { m_basicAudio = null; m_mediaControl = null; m_mediaEvent = null; }
protected void SyncAudioRenderer() { if (_audioRendererFilter != null) { //Log.Info("BDPlayer:set reference clock"); IMediaFilter mp = (IMediaFilter)_graphBuilder; IReferenceClock clock = (IReferenceClock)_audioRendererFilter; int hr = mp.SetSyncSource(null); hr = mp.SetSyncSource(clock); //Log.Info("BDPlayer:set reference clock:{0:X}", hr); _basicAudio = (IBasicAudio)_graphBuilder; } }
/// <summary> do cleanup and release DirectShow. </summary> protected void CloseInterfaces() { if (_graphBuilder == null) { return; } int hr; Log.Debug("BDPlayer: Cleanup DShow graph {0}", GUIGraphicsContext.InVmr9Render); try { BDOSDRenderer.Release(); if (_mediaCtrl != null) { int counter = 0; FilterState state; hr = _mediaCtrl.Stop(); hr = _mediaCtrl.GetState(10, out state); while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render) { Thread.Sleep(100); hr = _mediaCtrl.GetState(10, out state); counter++; if (counter >= 30) { if (state != FilterState.Stopped) Log.Error("BDPlayer: graph still running"); if (GUIGraphicsContext.InVmr9Render) Log.Error("BDPlayer: in renderer"); break; } } _mediaCtrl = null; } if (_vmr9 != null) { _vmr9.Enable(false); } if (_mediaEvt != null) { hr = _mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); _mediaEvt = null; } _videoWin = _graphBuilder as IVideoWindow; if (_videoWin != null) { hr = _videoWin.put_Visible(OABool.False); hr = _videoWin.put_Owner(IntPtr.Zero); _videoWin = null; } _mediaSeeking = null; _basicAudio = null; _basicVideo = null; _ireader = null; #region Cleanup Sebastiii if (VideoCodec != null) { DirectShowUtil.ReleaseComObject(VideoCodec, 5000); VideoCodec = null; Log.Info("BDPlayer: Cleanup VideoCodec"); } if (AudioCodec != null) { DirectShowUtil.ReleaseComObject(AudioCodec, 5000); AudioCodec = null; Log.Info("BDPlayer: Cleanup AudioCodec"); } if (_audioRendererFilter != null) { while (DirectShowUtil.ReleaseComObject(_audioRendererFilter) > 0) ; _audioRendererFilter = null; Log.Info("BDPlayer: Cleanup AudioRenderer"); } //Test to ReleaseComObject from PostProcessFilter list objects. if (PostProcessFilterVideo.Count > 0) { foreach (var ppFilter in PostProcessFilterVideo) { if (ppFilter.Value != null) DirectShowUtil.ReleaseComObject(ppFilter.Value, 5000); } PostProcessFilterVideo.Clear(); Log.Info("BDPlayer: Cleanup PostProcessVideo"); } //Test to ReleaseComObject from PostProcessFilter list objects. if (PostProcessFilterAudio.Count > 0) { foreach (var ppFilter in PostProcessFilterAudio) { if (ppFilter.Value != null) DirectShowUtil.ReleaseComObject(ppFilter.Value, 5000); } PostProcessFilterAudio.Clear(); Log.Info("BDPlayer: Cleanup PostProcessAudio"); } #endregion if (_interfaceBDReader != null) { DirectShowUtil.ReleaseComObject(_interfaceBDReader, 5000); _interfaceBDReader = null; } if (_graphBuilder != null) { DirectShowUtil.RemoveFilters(_graphBuilder); if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } while ((hr = DirectShowUtil.ReleaseComObject(_graphBuilder)) > 0) ; _graphBuilder = null; } if (_dvbSubRenderer != null) { _dvbSubRenderer.SetPlayer(null); _dvbSubRenderer = null; } if (_vmr9 != null) { _vmr9.SafeDispose(); _vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; } catch (Exception ex) { Log.Error("BDPlayer: Exception while cleaning DShow graph - {0} {1}", ex.Message, ex.StackTrace); } //switch back to directx windowed mode ExclusiveMode(false); }
private void 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 (locker) { // Relinquish ownership (IMPORTANT!) after hiding video window if (!this.isAudioOnly && this.videoWindow != null) { hr = this.videoWindow.put_Visible(OABool.False); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_Owner(IntPtr.Zero); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_MessageDrain(IntPtr.Zero); DsError.ThrowExceptionForHR(hr); } if (EVRControl != null) { Marshal.ReleaseComObject(EVRControl); EVRControl = null; } if (this.mediaEventEx != null) { hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); this.mediaEventEx = null; } if (this.mediaSeeking != null) this.mediaSeeking = null; if (this.mediaPosition != null) this.mediaPosition = null; if (this.mediaControl != null) this.mediaControl = null; if (this.basicAudio != null) this.basicAudio = null; if (this.basicVideo != null) this.basicVideo = null; if (this.videoWindow != null) this.videoWindow = null; if (this.graphBuilder != null) { while (Marshal.ReleaseComObject(this.graphBuilder) > 0) ; this.graphBuilder = null; } GC.Collect(); } } catch (Exception ex) { System.Windows.MessageBox.Show("CloseInterfaces: " + ex.Message, Languages.Translate("Error"), MessageBoxButton.OK, MessageBoxImage.Error); } }
public void StopPlayingAudio() { lock(fgmLock) { if(fgmState != FilterGraph.State.Stopped) { fgmState = FilterGraph.State.Stopped; if (fgm != null) { // We need to manually unblock the stream in case there is no data flowing if(rtpStream != null) { rtpStream.UnblockNextFrame(); } fgm.Stop(); iBA = null; } uiState |= (int)FAudioVideo.UIState.LocalAudioPlayStopped; ((FAudioVideo)form).UpdateAudioUI(uiState); } } }
/// <summary> /// Creation of the fgm and the adding / removing of filters needs to happen on the /// same thread. So make sure it all happens on the UI thread. /// </summary> private void _RtpStream_FirstFrameReceived() { lock(fgmLock) { DisposeFgm(); Debug.Assert(fgm == null); fgm = new FilgraphManagerClass(); IGraphBuilder iGB = (IGraphBuilder)fgm; rotID = FilterGraph.AddToRot(iGB); IBaseFilter rtpSource = RtpSourceClass.CreateInstance(); ((MSR.LST.MDShow.Filters.IRtpSource)rtpSource).Initialize(rtpStream); iGB.AddFilter(rtpSource, "RtpSource"); // Add the chosen audio renderer FilterInfo fi = SelectedSpeaker(); iGB.AddFilter(Filter.CreateBaseFilter(fi), fi.Name); iGB.Render(Filter.GetPin(rtpSource, _PinDirection.PINDIR_OUTPUT, Guid.Empty, Guid.Empty, false, 0)); iBA = (IBasicAudio)fgm; currentVolume = (int)Math.Round(Math.Pow(10.0, (2.0*(double)(iBA.Volume+10000))/10000.0)); iBA = null; uiState &= ~(int)FAudioVideo.UIState.RemoteAudioStopped; if(form != null) { ((FAudioVideo)form).UpdateAudioUI(uiState); } // FirstFrameReceived interprets fgmState as the *desired* state for the fgm // Because ResumePlayingAudio won't actually start if the state is already // Running, we change it to Stopped so that it will start if(IsPlaying && fgmState == FilterGraph.State.Running) { fgmState = FilterGraph.State.Stopped; ResumePlayingAudio(); } } }
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; }
private void StopAnimation() { if (isPlaying) { master.Stop(); if (master.form != null) { master.form.Invoke((MethodInvoker)delegate() { master.form.M_PrevSize.Enabled = true; }); } media.Stop(); if (eventEx != null) { eventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); eventEx = null; } if (window != null) { window.put_Visible(OABool.False); window.put_Owner(IntPtr.Zero); window = null; } iba = null; imp = null; igb = null; render = null; media = null; graph = null; master.Stop(); isPlaying = false; } }
// // Starts playback for the selected stream at the specified time // int OpenStream(string videopath, double videotime) { double td; // store stream duration; int hr = 0; // animate bt logo // logo_webbrowser.Refresh(); // cover overlay options with video or not // if overlay is active ////////if (OverlayButton.Checked) // Overlay button config - Melek ////////{ //////// VideoPanel.Width = VideoPlayerPanel.Width - OverlayPanel.Width; //////// OverlayBar.Location = new System.Drawing.Point(-1, -1); ; //////// OverlayBar.Text = ">"; ////////} ////////else ////////// if overlay is not active ////////{ //////// VideoPanel.Width = VideoPlayerPanel.Width - OverlayBar.Width; //////// OverlayBar.Location = new System.Drawing.Point(OverlayPanel.Width - OverlayBar.Width - 1, -1); ; //////// OverlayBar.Text = "<"; ////////} filename = videopath; try//Melek { if (filename == string.Empty) return -1; // this.graphBuilder = (IGraphBuilder)new FilterGraph(); this.graphBuilder = (IFilterGraph2)new FilterGraph(); // We manually add the VMR (video mixer/renderer) filter so that we can set it into "mixing" mode. // That is needed so that the VMR will deinterlace before playing back VideoMixingRenderer vmr = new VideoMixingRenderer(); //Tom's deinterlace changes graphBuilder.AddFilter((IBaseFilter)vmr, "vmr");//Tom's deinterlace changes IVMRFilterConfig vmrConfig = vmr as IVMRFilterConfig;//Tom's deinterlace changes int nRet = vmrConfig.SetNumberOfStreams(1);//Tom's deinterlace changes // BuildVideoGraph(videopath); //No more overlay - Melek hr = this.graphBuilder.RenderFile(filename, null);//MELek - instead of calling BuildVideoGraph function call RenderFile function directly DsError.ThrowExceptionForHR(hr);//Melek // QueryInterface for DirectShow interfaces this.mediaControl = (IMediaControl)this.graphBuilder; this.mediaEventEx = (IMediaEventEx)this.graphBuilder; this.mediaSeeking = (IMediaSeeking)this.graphBuilder; this.mediaPosition = (IMediaPosition)this.graphBuilder; // Query for video interfaces, which may not be relevant for audio files this.videoWindow = this.graphBuilder as IVideoWindow; this.basicVideo = this.graphBuilder as IBasicVideo; // Query for audio interfaces, which may not be relevant for video-only files this.basicAudio = this.graphBuilder as IBasicAudio; // Is this an audio-only file (no video component)? CheckVisibility(); // Have the graph signal event via window callbacks for performance hr = this.mediaEventEx.SetNotifyWindow(this.Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); //if (!this.isAudioOnly) //{ // Setup the video window hr = this.videoWindow.put_Owner(this.VideoPanel.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); hr = InitVideoWindow(1, 1); DsError.ThrowExceptionForHR(hr); GetFrameStepInterface(); //} //else //{ // Initialize the default player size // hr = InitPlayerWindow(); // DsError.ThrowExceptionForHR(hr); //EnablePlaybackMenu(true, MediaType.Audio); //} // Complete window initialization //CheckSizeMenu(menuFileSizeNormal); //this.isFullScreen = false; this.currentPlaybackRate = 1.0; #if DEBUG rot = new DsROTEntry(this.graphBuilder); #endif // check the mute button MuteStatus(); // Run the graph to play the media file this.mediaPosition.put_CurrentPosition(videotime); hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); this.currentState = PlayState.Running; UpdateMainTitle(); try { #if !DEMO this.mediaPosition.get_Duration(out td); #else td=vs.getDurationInSeconds(); #endif this.VideoProgressionBar.Minimum = 0; this.VideoProgressionBar.Maximum = (int)(td * 100); isTimer = true; // disable if raw 264 files are open (.264 or .h264) as they dont allow seeking if (videopath.EndsWith("264")) this.mediaSeeking = null; return 0; } catch (Exception ex) { //Global.log("Problem opening " + vs.path.Name + ".ts\n" + ex); Global.log("Problem opening " + vs.StreamFileName + "\n" + ex); //Melek - path.name => streamfilename EnablePlayback(false); //MElek return -1; } } catch (Exception ex) //Melek { // MessageBox.Show(ex.Message); EnablePlayback(false); return -1; } }
private void CloseInterfaces() { int hr = 0; try { lock(this) { // Relinquish ownership (IMPORTANT!) after hiding video window if (!this.isAudioOnly) { hr = this.videoWindow.put_Visible(OABool.False); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_Owner(IntPtr.Zero); DsError.ThrowExceptionForHR(hr); } if (this.mediaEventEx != null) { hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); } #if DEBUG if (rot != null) { rot.Dispose(); rot = null; } #endif // Release and zero DirectShow interfaces if (this.mediaEventEx != null) this.mediaEventEx = null; if (this.mediaSeeking != null) this.mediaSeeking = null; if (this.mediaPosition != null) this.mediaPosition = null; if (this.mediaControl != null) this.mediaControl = null; if (this.basicAudio != null) this.basicAudio = null; if (this.basicVideo != null) this.basicVideo = null; if (this.videoWindow != null) this.videoWindow = null; if (this.frameStep != null) this.frameStep = null; if (this.graphBuilder != null) Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null; GC.Collect(); } } catch { } }
private void Cleanup() { if (graphBuilder == null) { return; } int hr; Log.Info("RTSPPlayer:cleanup DShow graph"); try { if (_mediaCtrl != null) { int counter = 0; FilterState state; hr = _mediaCtrl.Stop(); hr = _mediaCtrl.GetState(10, out state); while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render) { Thread.Sleep(100); hr = _mediaCtrl.GetState(10, out state); counter++; if (counter >= 30) { if (state != FilterState.Stopped) Log.Error("RTSPPlayer: graph still running"); if (GUIGraphicsContext.InVmr9Render) Log.Error("RTSPPlayer: in renderer"); break; } } _mediaCtrl = null; } if (Vmr9 != null) { Vmr9.Enable(false); } if (mediaEvt != null) { hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); mediaEvt = null; } videoWin = graphBuilder as IVideoWindow; if (videoWin != null) { hr = videoWin.put_Visible(OABool.False); hr = videoWin.put_Owner(IntPtr.Zero); videoWin = null; } _mediaSeeking = null; mediaPos = null; basicAudio = null; basicVideo = null; videoWin = null; SubEngine.GetInstance().FreeSubtitles(); if (graphBuilder != null) { DirectShowUtil.RemoveFilters(graphBuilder); if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } DirectShowUtil.ReleaseComObject(graphBuilder); graphBuilder = null; } if (Vmr9 != null) { Vmr9.SafeDispose(); Vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; if (_mpegDemux != null) { Log.Info("cleanup mpegdemux"); while ((hr = DirectShowUtil.ReleaseComObject(_mpegDemux)) > 0) { ; } _mpegDemux = null; } if (_rtspSource != null) { Log.Info("cleanup _rtspSource"); while ((hr = DirectShowUtil.ReleaseComObject(_rtspSource)) > 0) { ; } _rtspSource = null; } if (_subtitleFilter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_subtitleFilter)) > 0) { ; } _subtitleFilter = null; if (this.dvbSubRenderer != null) { this.dvbSubRenderer.SetPlayer(null); } this.dvbSubRenderer = null; } if (vobSub != null) { Log.Info("cleanup vobSub"); while ((hr = DirectShowUtil.ReleaseComObject(vobSub)) > 0) { ; } vobSub = null; } } catch (Exception ex) { Log.Error("RTSPPlayer: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace); } //switch back to directx windowed mode Log.Info("RTSPPlayer: Disabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null); GUIWindowManager.SendMessage(msg); }
private void openMedia() { openFileDialog1.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*"; if (DialogResult.OK == openFileDialog1.ShowDialog()) { CleanUp(); m_objFilterGraph = new FilgraphManager(); m_objFilterGraph.RenderFile(openFileDialog1.FileName); m_objBasicAudio = m_objFilterGraph as IBasicAudio; try { m_objVideoWindow = m_objFilterGraph as IVideoWindow; m_objVideoWindow.Owner = (int)panel1.Handle; m_objVideoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN; m_objVideoWindow.SetWindowPosition(panel1.ClientRectangle.Left, panel1.ClientRectangle.Top, panel1.ClientRectangle.Width, panel1.ClientRectangle.Height); } catch(Exception) { m_objVideoWindow = null; } m_objMediaEvent = m_objFilterGraph as IMediaEvent; m_objMediaEventEx = m_objFilterGraph as IMediaEventEx; m_objMediaEventEx.SetNotifyWindow((int) this.Handle, WM_GRAPHNOTIFY, 0); m_objMediaPosition = m_objFilterGraph as IMediaPosition; m_objMediaControl = m_objFilterGraph as IMediaControl; this.Text = "Whistle- " + openFileDialog1.FileName + "]"; m_objMediaControl.Run(); m_CurrentStatus = MediaStatus.Running; } }
/// <summary> /// Sets the basic audio interface for controlling /// volume and balance /// </summary> protected void SetBasicAudioInterface(IBasicAudio basicAudio) { m_basicAudio = basicAudio; }
/// <summary> create the used COM components and get the interfaces. </summary> protected bool GetInterfaces() { VMR9Util.g_vmr9 = null; if (IsRadio == false) { Vmr9 = VMR9Util.g_vmr9 = new VMR9Util(); // switch back to directx fullscreen mode Log.Info("RTSPPlayer: Enabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 1, 0, null); GUIWindowManager.SendMessage(msg); } //Type comtype = null; //object comobj = null; DsRect rect = new DsRect(); rect.top = 0; rect.bottom = GUIGraphicsContext.form.Height; rect.left = 0; rect.right = GUIGraphicsContext.form.Width; try { graphBuilder = (IGraphBuilder)new FilterGraph(); Log.Info("RTSPPlayer: add source filter"); if (IsRadio == false) { bool AddVMR9 = VMR9Util.g_vmr9 != null && VMR9Util.g_vmr9.AddVMR9(graphBuilder); if (!AddVMR9) { Log.Error("RTSPPlayer:Failed to add VMR9 to graph"); return false; } VMR9Util.g_vmr9.Enable(false); } _mpegDemux = (IBaseFilter)new MPEG2Demultiplexer(); graphBuilder.AddFilter(_mpegDemux, "MPEG-2 Demultiplexer"); _rtspSource = (IBaseFilter)new RtpSourceFilter(); int hr = graphBuilder.AddFilter((IBaseFilter)_rtspSource, "RTSP Source Filter"); if (hr != 0) { Log.Error("RTSPPlayer:unable to add RTSP source filter:{0:X}", hr); return false; } // add preferred video & audio codecs Log.Info("RTSPPlayer: add video/audio codecs"); string strVideoCodec = ""; string strAudioCodec = ""; string strAudiorenderer = ""; int intFilters = 0; // FlipGer: count custom filters string strFilters = ""; // FlipGer: collect custom filters string postProcessingFilterSection = "mytv"; using (Settings xmlreader = new MPSettings()) { if (_mediaType == g_Player.MediaType.Video) { strVideoCodec = xmlreader.GetValueAsString("movieplayer", "mpeg2videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("movieplayer", "mpeg2audiocodec", ""); strAudiorenderer = xmlreader.GetValueAsString("movieplayer", "audiorenderer", "Default DirectSound Device"); postProcessingFilterSection = "movieplayer"; } else { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", ""); strAudiorenderer = xmlreader.GetValueAsString("mytv", "audiorenderer", "Default DirectSound Device"); postProcessingFilterSection = "mytv"; } enableDvbSubtitles = xmlreader.GetValueAsBool("tvservice", "dvbsubtitles", false); // FlipGer: load infos for custom filters int intCount = 0; while (xmlreader.GetValueAsString(postProcessingFilterSection, "filter" + intCount.ToString(), "undefined") != "undefined") { if (xmlreader.GetValueAsBool(postProcessingFilterSection, "usefilter" + intCount.ToString(), false)) { strFilters += xmlreader.GetValueAsString(postProcessingFilterSection, "filter" + intCount.ToString(), "undefined") + ";"; intFilters++; } intCount++; } } string extension = Path.GetExtension(m_strCurrentFile).ToLowerInvariant(); if (IsRadio == false) { if (strVideoCodec.Length > 0) { DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); } } if (strAudioCodec.Length > 0) { DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); } if (enableDvbSubtitles == true) { try { _subtitleFilter = SubtitleRenderer.GetInstance().AddSubtitleFilter(graphBuilder); SubtitleRenderer.GetInstance().SetPlayer(this); dvbSubRenderer = SubtitleRenderer.GetInstance(); } catch (Exception e) { Log.Error(e); } } Log.Debug("Is subtitle fitler null? {0}", (_subtitleFilter == null)); // FlipGer: add custom filters to graph string[] arrFilters = strFilters.Split(';'); for (int i = 0; i < intFilters; i++) { DirectShowUtil.AddFilterToGraph(graphBuilder, arrFilters[i]); } if (strAudiorenderer.Length > 0) { audioRendererFilter = DirectShowUtil.AddAudioRendererToGraph(graphBuilder, strAudiorenderer, false); } Log.Info("RTSPPlayer: load:{0}", m_strCurrentFile); IFileSourceFilter interfaceFile = (IFileSourceFilter)_rtspSource; if (interfaceFile == null) { Log.Error("RTSPPlayer:Failed to get IFileSourceFilter"); return false; } //Log.Info("RTSPPlayer: open file:{0}",filename); hr = interfaceFile.Load(m_strCurrentFile, null); if (hr != 0) { Log.Error("RTSPPlayer:Failed to open file:{0} :0x{1:x}", m_strCurrentFile, hr); return false; } #region connect rtspsource->demux Log.Info("RTSPPlayer:connect rtspsource->mpeg2 demux"); IPin pinTsOut = DsFindPin.ByDirection((IBaseFilter)_rtspSource, PinDirection.Output, 0); if (pinTsOut == null) { Log.Info("RTSPPlayer:failed to find output pin of tsfilesource"); return false; } IPin pinDemuxIn = DsFindPin.ByDirection(_mpegDemux, PinDirection.Input, 0); if (pinDemuxIn == null) { Log.Info("RTSPPlayer:failed to find output pin of tsfilesource"); return false; } hr = graphBuilder.Connect(pinTsOut, pinDemuxIn); if (hr != 0) { Log.Info("RTSPPlayer:failed to connect rtspsource->mpeg2 demux:{0:X}", hr); return false; } DirectShowUtil.ReleaseComObject(pinTsOut); DirectShowUtil.ReleaseComObject(pinDemuxIn); #endregion #region render demux output pins if (IsRadio) { Log.Info("RTSPPlayer:render audio demux outputs"); IEnumPins enumPins; _mpegDemux.EnumPins(out enumPins); IPin[] pins = new IPin[2]; int fetched = 0; while (enumPins.Next(1, pins, out fetched) == 0) { if (fetched != 1) { break; } PinDirection direction; pins[0].QueryDirection(out direction); if (direction == PinDirection.Input) { continue; } IEnumMediaTypes enumMediaTypes; pins[0].EnumMediaTypes(out enumMediaTypes); AMMediaType[] mediaTypes = new AMMediaType[20]; int fetchedTypes; enumMediaTypes.Next(20, mediaTypes, out fetchedTypes); for (int i = 0; i < fetchedTypes; ++i) { if (mediaTypes[i].majorType == MediaType.Audio) { graphBuilder.Render(pins[0]); break; } } } } else { Log.Info("RTSPPlayer:render audio/video demux outputs"); IEnumPins enumPins; _mpegDemux.EnumPins(out enumPins); IPin[] pins = new IPin[2]; int fetched = 0; while (enumPins.Next(1, pins, out fetched) == 0) { if (fetched != 1) { break; } PinDirection direction; pins[0].QueryDirection(out direction); if (direction == PinDirection.Input) { continue; } graphBuilder.Render(pins[0]); } } #endregion // Connect DVB subtitle filter pins in the graph if (_mpegDemux != null && enableDvbSubtitles == true) { IMpeg2Demultiplexer demuxer = _mpegDemux as IMpeg2Demultiplexer; hr = demuxer.CreateOutputPin(GetTSMedia(), "Pcr", out _pinPcr); if (hr == 0) { Log.Info("RTSPPlayer:_pinPcr OK"); IPin pDemuxerPcr = DsFindPin.ByName(_mpegDemux, "Pcr"); IPin pSubtitlePcr = DsFindPin.ByName(_subtitleFilter, "Pcr"); hr = graphBuilder.Connect(pDemuxerPcr, pSubtitlePcr); } else { Log.Info("RTSPPlayer:Failed to create _pinPcr in demuxer:{0:X}", hr); } hr = demuxer.CreateOutputPin(GetTSMedia(), "Subtitle", out _pinSubtitle); if (hr == 0) { Log.Info("RTSPPlayer:_pinSubtitle OK"); IPin pDemuxerSubtitle = DsFindPin.ByName(_mpegDemux, "Subtitle"); IPin pSubtitle = DsFindPin.ByName(_subtitleFilter, "In"); hr = graphBuilder.Connect(pDemuxerSubtitle, pSubtitle); } else { Log.Info("RTSPPlayer:Failed to create _pinSubtitle in demuxer:{0:X}", hr); } hr = demuxer.CreateOutputPin(GetTSMedia(), "PMT", out _pinPMT); if (hr == 0) { Log.Info("RTSPPlayer:_pinPMT OK"); IPin pDemuxerSubtitle = DsFindPin.ByName(_mpegDemux, "PMT"); IPin pSubtitle = DsFindPin.ByName(_subtitleFilter, "PMT"); hr = graphBuilder.Connect(pDemuxerSubtitle, pSubtitle); } else { Log.Info("RTSPPlayer:Failed to create _pinPMT in demuxer:{0:X}", hr); } } if (IsRadio == false) { if (!VMR9Util.g_vmr9.IsVMR9Connected) { //VMR9 is not supported, switch to overlay Log.Info("RTSPPlayer: vmr9 not connected"); _mediaCtrl = null; Cleanup(); return false; } VMR9Util.g_vmr9.SetDeinterlaceMode(); } _mediaCtrl = (IMediaControl)graphBuilder; mediaEvt = (IMediaEventEx)graphBuilder; _mediaSeeking = (IMediaSeeking)graphBuilder; mediaPos = (IMediaPosition)graphBuilder; basicAudio = graphBuilder as IBasicAudio; //DirectShowUtil.SetARMode(graphBuilder,AspectRatioMode.Stretched); DirectShowUtil.EnableDeInterlace(graphBuilder); if (VMR9Util.g_vmr9 != null) { m_iVideoWidth = VMR9Util.g_vmr9.VideoWidth; m_iVideoHeight = VMR9Util.g_vmr9.VideoHeight; } if (audioRendererFilter != null) { Log.Info("RTSPPlayer9:set reference clock"); IMediaFilter mp = graphBuilder as IMediaFilter; IReferenceClock clock = audioRendererFilter as IReferenceClock; hr = mp.SetSyncSource(null); hr = mp.SetSyncSource(clock); Log.Info("RTSPPlayer9:set reference clock:{0:X}", hr); } Log.Info("RTSPPlayer: graph build successfull"); return true; } catch (Exception ex) { Error.SetError("Unable to play movie", "Unable build graph for VMR9"); Log.Error("RTSPPlayer:exception while creating DShow graph {0} {1}", ex.Message, ex.StackTrace); CloseInterfaces(); return false; } }
public void ResumePlayingAudio() { lock(fgmLock) { if(fgmState != FilterGraph.State.Running) { fgmState = FilterGraph.State.Running; if (fgm != null) { iBA = (IBasicAudio)fgm; // Note: We use the currentVolume member to set the volume. // This member is actually initialized in SetVolume // in case SetVolume was called before the fgm (and iBA) // was created (before stream added is called) SetVolume(currentVolume); // MethodInvoke the PositionVolumeSlider to set the position of the slider in the AV form // Note: There is no parameter. The AV from reads the volume parameter using the // volume accessor in AudioCapability. ((FAudioVideo)form).PositionVolumeSlider(); // We need to manually block the stream to reset its state in case it // became inconsistent during shutdown if(rtpStream != null) { rtpStream.BlockNextFrame(); } fgm.Run(); } uiState &= ~(int)FAudioVideo.UIState.LocalAudioPlayStopped; ((FAudioVideo)form).UpdateAudioUI(uiState); } } }
private void Cleanup() { if (graphBuilder == null) { return; } int hr; Log.Info("RTSPPlayer:cleanup DShow graph"); try { if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.Vmr9MediaCtrl(_mediaCtrl); VMR9Util.g_vmr9.Enable(false); } if (mediaEvt != null) { hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); } videoWin = graphBuilder as IVideoWindow; if (videoWin != null && GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR) { videoWin.put_Owner(IntPtr.Zero); videoWin.put_Visible(OABool.False); } _mediaCtrl = null; mediaEvt = null; _mediaSeeking = null; mediaPos = null; basicAudio = null; basicVideo = null; videoWin = null; SubEngine.GetInstance().FreeSubtitles(); if (graphBuilder != null) { DirectShowUtil.RemoveFilters(graphBuilder); if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } DirectShowUtil.FinalReleaseComObject(graphBuilder); graphBuilder = null; } if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.SafeDispose(); VMR9Util.g_vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; if (_mpegDemux != null) { Log.Info("cleanup mpegdemux"); DirectShowUtil.FinalReleaseComObject(_mpegDemux); _mpegDemux = null; } if (_rtspSource != null) { Log.Info("cleanup _rtspSource"); DirectShowUtil.FinalReleaseComObject(_rtspSource); _rtspSource = null; } if (_subtitleFilter != null) { DirectShowUtil.FinalReleaseComObject(_subtitleFilter); _subtitleFilter = null; if (this.dvbSubRenderer != null) { this.dvbSubRenderer.SetPlayer(null); } this.dvbSubRenderer = null; } if (vobSub != null) { Log.Info("cleanup vobSub"); DirectShowUtil.FinalReleaseComObject(vobSub); vobSub = null; } } catch (Exception ex) { Log.Error("RTSPPlayer: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace); } //switch back to directx windowed mode Log.Info("RTSPPlayer: Disabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null); GUIWindowManager.SendMessage(msg); }
public override void Init() { if (!isPlaying) { string Filename = ""; float size = 0; double Max = 0; int volume = 0; graph = new FilterGraph() as IFilterGraph; media = graph as IMediaControl; eventEx = media as IMediaEventEx; igb = media as IGraphBuilder; imp = igb as IMediaPosition; master.form.Invoke((MethodInvoker)delegate() { Filename = master.form.M_Filename.Text; media.RenderFile(Filename); size = (float)master.form.M_PrevSize.Value; master.form.M_PrevSize.Enabled = false; imp.get_Duration(out Max); master.form.M_Seek.Maximum = (int)(Max); master.form.M_Seek.Value = 0; volume = master.form.M_Volume.Value; span = (uint)(1000000.0f / master.form.M_CollectFPS); }); graph.FindFilterByName("Video Renderer", out render); if (render != null) { window = render as IVideoWindow; window.put_WindowStyle( WindowStyle.Caption | WindowStyle.Child ); window.put_WindowStyleEx( WindowStyleEx.ToolWindow ); window.put_Caption("ElectronicBoard - VideoPrev -"); int Width, Height, Left, Top; window.get_Width(out Width); window.get_Height(out Height); window.get_Left(out Left); window.get_Top(out Top); renderSize.Width = (int)(Width * size); renderSize.Height = (int)(Height * size); Aspect = (float)renderSize.Height / (float)renderSize.Width; window.SetWindowPosition(Left, Top, renderSize.Width, renderSize.Height); eventEx = media as IMediaEventEx; eventEx.SetNotifyWindow(master.form.Handle, WM_DirectShow, IntPtr.Zero); media.Run(); foreach (Process p in Process.GetProcesses()) { if (p.MainWindowTitle == "ElectronicBoard - VideoPrev -") { renderwindow = p.MainWindowHandle; break; } } isPlaying = true; iba = media as IBasicAudio; iba.put_Volume(volume); //master.form.checkBox3_CheckedChanged(null, null); master.Start(); } } }
private void DisposeFgm() { lock(fgmLock) { if (fgm != null) { // We need to manually unblock the stream in case there is no data flowing if(rtpStream != null) { rtpStream.UnblockNextFrame(); } FilterGraph.RemoveFromRot(rotID); fgm.Stop(); FilterGraph.RemoveAllFilters(fgm); fgm = null; iBA = null; } } }
private void PlayMovieInWindow(string filename) { int hr = 0; if (filename == string.Empty) return; this.graphBuilder = (IGraphBuilder) new FilterGraph(); // Have the graph builder construct its the appropriate graph automatically hr = this.graphBuilder.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); // QueryInterface for DirectShow interfaces this.mediaControl = (IMediaControl) this.graphBuilder; this.mediaEventEx = (IMediaEventEx) this.graphBuilder; this.mediaSeeking = (IMediaSeeking) this.graphBuilder; this.mediaPosition = (IMediaPosition) this.graphBuilder; // Query for video interfaces, which may not be relevant for audio files this.videoWindow = this.graphBuilder as IVideoWindow; this.basicVideo = this.graphBuilder as IBasicVideo; // Query for audio interfaces, which may not be relevant for video-only files this.basicAudio = this.graphBuilder as IBasicAudio; // Is this an audio-only file (no video component)? CheckVisibility(); // Have the graph signal event via window callbacks for performance hr = this.mediaEventEx.SetNotifyWindow(this.Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); if (!this.isAudioOnly) { // Setup the video window hr = this.videoWindow.put_Owner(this.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); hr = InitVideoWindow(1, 1); DsError.ThrowExceptionForHR(hr); GetFrameStepInterface(); } else { // Initialize the default player size and enable playback menu items hr = InitPlayerWindow(); DsError.ThrowExceptionForHR(hr); EnablePlaybackMenu(true, MediaType.Audio); } // Complete window initialization CheckSizeMenu(menuFileSizeNormal); this.isFullScreen = false; this.currentPlaybackRate = 1.0; UpdateMainTitle(); #if DEBUG rot = new DsROTEntry(this.graphBuilder); #endif this.Focus(); // Run the graph to play the media file hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); this.currentState=PlayState.Running; }
/// <summary> do cleanup and release DirectShow. </summary> protected virtual void CloseDVDInterfaces() { if (_graphBuilder == null) { return; } int hr; try { logger.Info("DVDPlayer:cleanup DShow graph"); if (_mediaCtrl != null) { hr = _mediaCtrl.Stop(); _mediaCtrl = null; } _state = PlayState.Stopped; _mediaEvt = null; _visible = false; _videoWin = null; // videoStep = null; _dvdCtrl = null; _dvdInfo = null; _basicVideo = null; _basicAudio = null; _mediaPos = null; _mediaSeek = null; _mediaStep = null; //if (_vmr7 != null) //{ // _vmr7.RemoveVMR7(); //} //_vmr7 = null; if (_vmr9Filter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_vmr9Filter)) > 0) { ; } _vmr9Filter = null; } if (_dvdbasefilter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_dvdbasefilter)) > 0) { ; } _dvdbasefilter = null; } if (_cmdOption != null) { DirectShowUtil.ReleaseComObject(_cmdOption); } _cmdOption = null; _pendingCmd = false; if (_line21Decoder != null) { while ((hr = DirectShowUtil.ReleaseComObject(_line21Decoder)) > 0) { ; } _line21Decoder = null; } if (_graphBuilder != null) { DirectShowUtil.RemoveFilters(_graphBuilder); if (_rotEntry != null) { _rotEntry.Dispose(); _rotEntry = null; } while ((hr = DirectShowUtil.ReleaseComObject(_graphBuilder)) > 0) { ; } _graphBuilder = null; } if (_dvdGraph != null) { while ((hr = DirectShowUtil.ReleaseComObject(_dvdGraph)) > 0) { ; } _dvdGraph = null; } _state = PlayState.Init; } catch (Exception ex) { logger.Error("DVDPlayer:exception while cleanuping DShow graph {0} {1}", ex.Message, ex.StackTrace); } }
private void CloseInterfaces() { 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 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; } }