예제 #1
0
 //
 //method that update the graph filter and/or gui controls
 //when we have received a message that the media file is done playing
 //
 private void OnClipCompleted()
 {
     graphState = State.Stopped;
     if (mediaCtrl == null)
     {
         return;
     }
     mediaCtrl.Stop();
     if (!bThru && bLoop)
     {
         if (isSeeking)
         {
             mediaPos.put_CurrentPosition(0.0);
             mediaCtrl.Run();
         }
     }
     if (bThru)
     {
         if ((movieFiles.SelectedIndex + 1) < nbFiles)
         {
             movieFiles.SelectedIndex++;
         }
         else
         {
             movieFiles.SelectedIndex = 0;
         }
     }
 }
예제 #2
0
        public void GrabFrame(string FileName, string outputFileName, double timeindex)
        {
            FilterState state;
            int         tr = 0;

            CloseInterfaces();
            BuildGraph(FileName);
            int hr = mediaPosition.put_CurrentPosition(timeindex); // Seeking.   .Run();

            mediaControl.Run();
            tr = mediaControl.GetState(0, out state);
            while (state != FilterState.Running && tr != 0)
            {
                tr = mediaControl.GetState(0, out state);
            }
            ;


            mediaControl.Pause();
            tr = mediaControl.GetState(0, out state);
            while (state != FilterState.Running && tr != 0)
            {
                tr = mediaControl.GetState(0, out state);
            }
            ;

//             DsError.ThrowExceptionForHR(hr);
            snapImage(outputFileName);
            CloseInterfaces();
        }
예제 #3
0
 private void trackBar1_Scroll(object sender, EventArgs e)
 {
     if (mediaPosition != null)
     {
         mediaPosition.put_CurrentPosition(trackBar1.Value);
     }
 }
예제 #4
0
        public void SkipForward(double percentagetoskip)
        {
            //double factor = percentagetoskip / 100;


            // If we are playing
            if (m_State == GraphState.Running)
            {
                int hr = m_mediaCtrl.Pause();
                DsError.ThrowExceptionForHR(hr);
                m_State = GraphState.Paused;

                DirectShowLib.OABool result;
                m_mediaPosition.CanSeekForward(out result);
                if (result == OABool.True)
                {
                    //double plltime;
                    //m_mediaPosition.get_StopTime(out plltime);

                    //m_mediaPosition.put_CurrentPosition(plltime * factor);
                    m_mediaPosition.put_CurrentPosition(percentagetoskip);
                    hr = m_mediaCtrl.Run();
                    DsError.ThrowExceptionForHR(hr);
                    m_State = GraphState.Running;
                }
            }
        }
예제 #5
0
        // Reset the clip back to the beginning
        public void Rewind()
        {
            int hr;

            IMediaPosition imp = m_FilterGraph as IMediaPosition;

            hr = imp.put_CurrentPosition(0);
        }
 protected override void SetMediaPosition(double pos)
 {
     if (mediaPosition != null)
     {
         int hr = mediaPosition.put_CurrentPosition(pos / durationScaleFactor);
         DsError.ThrowExceptionForHR(hr);
     }
 }
예제 #7
0
        // Reset the clip back to the beginning
        public void Rewind()
        {
            int hr;

            IMediaPosition imp = m_graphBuilder as IMediaPosition;

            hr = imp.put_CurrentPosition(0);
        }
예제 #8
0
 /// <summary>Reset the clip back to the beginning</summary>
 public void Rewind()
 {
     lock (m_controls_lock)
     {
         if (m_media_position != null)
         {
             DsError.ThrowExceptionForHR(m_media_position.put_CurrentPosition(0));
         }
     }
 }
예제 #9
0
        /// <summary>
        /// Rewinds the video to the start and stops
        /// </summary>
        public void Rewind()
        {
            IMediaPosition imp = fg as IMediaPosition;

            if (imp != null)
            {
                imp.put_CurrentPosition(0);
            }

            // force a new play
            Stop();
        }
예제 #10
0
        public override void SeekRelative(double dTime)
        {
            if (_state != PlayState.Init)
            {
                if (_mediaCtrl != null && mediaPos != null)
                {
                    double dCurTime;
                    mediaPos.get_CurrentPosition(out dCurTime);

                    dTime = dCurTime + dTime;
                    if (dTime < 0.0d)
                    {
                        dTime = 0.0d;
                    }
                    if (dTime < Duration)
                    {
                        mediaPos.put_CurrentPosition(dTime);
                    }
                }
            }
        }
예제 #11
0
        /// <summary>
        /// Queries the current video source for its capabilities regarding seeking and time info.
        /// The graph should be fully constructed for accurate information
        /// </summary>
        protected void QuerySeekingCapabilities()
        {
            try
            {
                _mediaSeeking.SetTimeFormat(TimeFormat.MediaTime);
                //get capabilities from the graph, and see what it supports that interests us
                AMSeekingSeekingCapabilities caps;
                int    r       = _mediaSeeking.GetCapabilities(out caps);
                long   lTest   = 0;
                double dblTest = 0;
                if (r != 0)
                {
                    _seek_canGetCurrentPos = false;
                    _seek_canSeek          = false;
                    _seek_canGetDuration   = false;
                }
                else    //if we were able to read the capabilities, then determine if the capability works, both by checking the
                // advertisement, and actually trying it out.
                {
                    _seek_canSeek = ((caps & AMSeekingSeekingCapabilities.CanSeekAbsolute) == AMSeekingSeekingCapabilities.CanSeekAbsolute) &&
                                    (_mediaSeeking.SetPositions(0, AMSeekingSeekingFlags.AbsolutePositioning,
                                                                null, AMSeekingSeekingFlags.NoPositioning) == 0);

                    _seek_canGetDuration = ((caps & AMSeekingSeekingCapabilities.CanGetDuration) == AMSeekingSeekingCapabilities.CanGetDuration) &&
                                           (_mediaSeeking.GetDuration(out lTest) == 0);

                    _seek_canGetCurrentPos = ((caps & AMSeekingSeekingCapabilities.CanGetCurrentPos) == AMSeekingSeekingCapabilities.CanGetCurrentPos) &&
                                             (_mediaSeeking.GetCurrentPosition(out lTest) == 0);
                }

                //check capabilities for the IMediaPosition interface
                _pos_canSeek          = (_mediaPosition.put_CurrentPosition(0) == 0);
                _pos_canGetDuration   = (_mediaPosition.get_Duration(out dblTest) == 0);
                _pos_canGetCurrentPos = (_mediaPosition.get_CurrentPosition(out dblTest) == 0);
            }
            catch (Exception)
            {
                _seek_canSeek = false;
                _pos_canSeek  = false;
            }
        }
예제 #12
0
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (state == FilterState.Stopped)
            {
                return;
            }

            if (_mediaCtrl != null)
            {
                int hr = _mediaCtrl.Stop();
                DsError.ThrowExceptionForHR(hr);
                state = FilterState.Stopped;
            }
            // Seek back to the start.
            if (_mediaPos != null)
            {
                _offsetseek   = 0;
                seekbar.Value = 0;
                _mediaPos.put_CurrentPosition(0);
            }
        }
예제 #13
0
        void TestPosition()
        {
            int hr;

            double pllTime;

            Thread.Sleep(1500);

            hr = m_mediaPosition.get_CurrentPosition(out pllTime);
            DsError.ThrowExceptionForHR(hr);

            Debug.Assert(pllTime > 1.0, "get_CurrentPosition");

            hr = m_mediaPosition.put_CurrentPosition(0);
            DsError.ThrowExceptionForHR(hr);

            hr = m_mediaPosition.get_CurrentPosition(out pllTime);
            DsError.ThrowExceptionForHR(hr);

            Debug.Assert(pllTime < 1.0, "get_CurrentPosition");
        }
 private void trackBar_mediapos_Scroll(object sender, EventArgs e)
 {
     m_mediapos.put_CurrentPosition((double)trackBar_mediapos.Value);
 }
예제 #15
0
        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();
        }
예제 #16
0
        private void PlayMovieInWindow(string filename)
        {
            fps = 0;
            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.None);
                MFError.ThrowExceptionForHR(hr);
            }

            // Have the graph builder construct its the appropriate graph automatically
            hr = this.graphBuilder.RenderFile(filename, null);
            DsError.ThrowExceptionForHR(hr);

            if (EVRControl == null)
            {
                //Ищем рендерер и отключаем соблюдение аспекта (аспект будет определяться размерами видео-окна)
                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.None));
                }
                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.None));
                    }
                }
            }

            // 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 = (EVRControl == null) ? this.graphBuilder as IVideoWindow : null;
            this.basicVideo = (EVRControl == null) ? this.graphBuilder as IBasicVideo : null;

            // Query for audio interfaces, which may not be relevant for video-only files
            this.basicAudio = this.graphBuilder as IBasicAudio;
            basicAudio.put_Volume(VolumeSet); //Ввод в ДиректШоу значения VolumeSet для установки громкости

            // Is this an audio-only file (no video component)?
            CheckIsAudioOnly();
            if (!this.IsAudioOnly)
            {
                if (videoWindow != null)
                {
                    // Setup the video window
                    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);

                    //Определяем fps
                    double AvgTimePerFrame;
                    hr = basicVideo.get_AvgTimePerFrame(out AvgTimePerFrame);
                    DsError.ThrowExceptionForHR(hr);
                    fps = (1.0 / AvgTimePerFrame);
                }
                else if (EVRControl != null)
                {
                    //Определяем fps
                    DetermineEVRFPS();
                }

                //Ловим ошибку Ависинта
                IsAviSynthError = false;
                if (NaturalDuration.TotalMilliseconds == 10000.0)
                {
                    //Признаки ошибки: duration=10000.0 и fps=24 (округлённо)
                    if ((int)fps == 24 || fps == 0) IsAviSynthError = true;
                }

                MoveVideoWindow();
            }
            else
            {
                if (VHost != null)
                {
                    VHost.Dispose();
                    VHost = null;
                    VHandle = IntPtr.Zero;
                    VHostElement.Child = null;
                    VHostElement.Visibility = Visibility.Collapsed;
                    VHostElement.Width = VHostElement.Height = 0;
                    VHostElement.Margin = new Thickness(0);
                }

                //Ловим ошибку Ависинта 2 (когда нет видео окна)
                IsAviSynthError = (NaturalDuration.TotalMilliseconds == 10000.0);

                if (m.isvideo)
                {
                    //Видео должно было быть..
                    PreviewError("NO VIDEO", Brushes.Gainsboro);
                }
            }

            //Если выше не удалось определить fps - берём значение из массива
            if (fps == 0) fps = Calculate.ConvertStringToDouble(m.outframerate);

            // Have the graph signal event via window callbacks for performance
            hr = this.mediaEventEx.SetNotifyWindow(this.source.Handle, WMGraphNotify, IntPtr.Zero);
            DsError.ThrowExceptionForHR(hr);

            if (mediaload == MediaLoad.update) //Перенесено из HandleGraphEvent, теперь позиция устанавливается до начала воспроизведения, т.е. за один заход, а не за два
            {
                if (NaturalDuration >= oldpos) //Позиционируем только если нужная позиция укладывается в допустимый диапазон
                    mediaPosition.put_CurrentPosition(oldpos.TotalSeconds);
                //else
                //    mediaPosition.put_CurrentPosition(NaturalDuration.TotalSeconds); //Ограничиваем позицию длиной клипа
            }

            // Run the graph to play the media file
            if (currentState == PlayState.Running)
            {
                //Продолжение воспроизведения, если статус до обновления был Running
                DsError.ThrowExceptionForHR(this.mediaControl.Run());
                SetPauseIcon();
            }
            else
            {
                //Запуск с паузы, если была пауза или это новое открытие файла
                DsError.ThrowExceptionForHR(this.mediaControl.Pause());
                this.currentState = PlayState.Paused;
                SetPlayIcon();
            }
        }