protected override void Initialize(IGraphBuilder pGraphBuilder, IntPtr hMediaWindow)
        {
            object factoryObject   = null;
            object presenterObject = null;

            try
            {
                int hr = ClassFactory.GetEvrPresenterClassFactory(ref CLSID_CustomEVRPresenter, ref ClassFactory.IID_ClassFactory, out factoryObject);
                Marshal.ThrowExceptionForHR(hr);

                IClassFactory factory = (IClassFactory)factoryObject;

                var iidPresenter = typeof(IMFVideoPresenter).GUID;
                hr = factory.CreateInstance(null, ref iidPresenter, out presenterObject);
                Marshal.ThrowExceptionForHR(hr);

                IMFVideoPresenter presenter = (IMFVideoPresenter)presenterObject;

                IMFVideoRenderer renderer = (IMFVideoRenderer)BaseFilter; // will be released when IBaseFilter is released
                renderer.InitializeRenderer(null, presenter);

                IMFGetService pMFGetService = (IMFGetService)BaseFilter; // will be released when IBaseFilter is released
                object        o;
                var           serviceId = ServiceID.EnhancedVideoRenderer;
                var           iidImfVideoDisplayControl = typeof(IMFVideoDisplayControl).GUID;
                Marshal.ThrowExceptionForHR(pMFGetService.GetService(ref serviceId, ref iidImfVideoDisplayControl, out o));
                _pMFVideoDisplayControl = (IMFVideoDisplayControl)o;

                _pMFVideoDisplayControl.SetVideoWindow(hMediaWindow);
                _pMFVideoDisplayControl.SetAspectRatioMode(MFVideoAspectRatioMode.MFVideoARMode_None);

                _pvpPresenterConfig = (IPvpPresenterConfig)presenterObject;
                _pvpPresenterConfig.SetBufferCount(PRESENTER_BUFFER_COUNT);

                _pvpPresenterHook.HookUp(presenterObject);

                // as EVR requests IMFVideoDisplayControl from the presenter and our custom presenter implements IPvpPresenter and IPvpPresenterConfig
                // presenterObject and _pMFVideoDisplayControl point to the same RCW

                presenterObject = null; // we will release the presenter when releasing _pMFVideoDisplayControl
            }
            catch
            {
                _pMFVideoDisplayControl = null;
                _pvpPresenterConfig     = null;
            }
            finally
            {
                if (factoryObject != null)
                {
                    Marshal.FinalReleaseComObject(factoryObject);
                }

                if (presenterObject != null)
                {
                    Marshal.FinalReleaseComObject(presenterObject);
                }
            }
        }
Esempio n. 2
0
        protected override void CloseInterfaces()
        {
            if (_pMfVideoDisplayControl != null)
            {
                _pMfVideoDisplayControl.SetVideoWindow(IntPtr.Zero);
                Marshal.FinalReleaseComObject(_pMfVideoDisplayControl);
                _pMfVideoDisplayControl = null;
            }

            base.CloseInterfaces(); // release pBaseFilter
        }
Esempio n. 3
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }

            if (_vw != null)
            {
                int hr = _vw.put_Owner(IntPtr.Zero);
                _vw = null;
            }

            if (_evr != null)
            {
                try
                {
                    _evr.SetVideoWindow(IntPtr.Zero);
                }
                catch (Exception ex)
                {
#if DEBUG
                    MessageBox.Show(ex.Message, "Failed to reset EVR Window");
#endif
                }
                finally
                {
                    _evr = null;
                }
            }

            if (_detachedWindow != null)
            {
                _detachedWindow.Close();
            }

            base.Dispose(disposing);
        }
Esempio n. 4
0
        private void InitializeEVR(IBaseFilter pEVR, int dwStreams, out IMFVideoDisplayControl ppDisplay)
        {
            IMFVideoRenderer pRenderer;

            IEVRFilterConfig  pConfig;
            IMFVideoPresenter pPresenter;

            pPresenter = new EVRCustomPresenter();

            pRenderer = (IMFVideoRenderer)pEVR;

            pRenderer.InitializeRenderer(null, pPresenter);

            object o;

            MediaFoundation.IMFGetService pGetService;
            pGetService = (MediaFoundation.IMFGetService)pEVR;
            pGetService.GetService(MediaFoundation.MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out o);

            try
            {
                pDisplay = (IMFVideoDisplayControl)o;
            }
            catch
            {
                Marshal.ReleaseComObject(o);
                throw;
            }

            pDisplay.SetVideoWindow(panel.Handle);

            if (dwStreams > 1)
            {
                pConfig = (IEVRFilterConfig)pEVR;
                pConfig.SetNumberOfStreams(dwStreams);
            }

            Rectangle r = ClientRectangle;

            MediaFoundation.Misc.MFRect rc = new MediaFoundation.Misc.MFRect(r.Left, r.Top, r.Right, r.Bottom);

            pDisplay.SetVideoPosition(null, rc);

            ppDisplay = pDisplay;
        }
Esempio n. 5
0
        protected override void Initialize(IGraphBuilder pGraphBuilder, IntPtr hMediaWindow)
        {
            // QUERY the EVR interfaces
            try
            {
                IMFGetService pMFGetService = (IMFGetService)BaseFilter; // will be released when IBaseFilter is released
                object        o;
                Guid          serviceId = ServiceID.EnhancedVideoRenderer;
                Guid          IID_IMFVideoDisplayControl = typeof(IMFVideoDisplayControl).GUID;
                Marshal.ThrowExceptionForHR(pMFGetService.GetService(ref serviceId, ref IID_IMFVideoDisplayControl, out o));
                _pMfVideoDisplayControl = (IMFVideoDisplayControl)o;

                _pMfVideoDisplayControl.SetVideoWindow(hMediaWindow);
                _pMfVideoDisplayControl.SetAspectRatioMode(MFVideoAspectRatioMode.MFVideoARMode_None);
            }
            catch (Exception e)
            {
                throw new FilterGraphBuilderException(GraphBuilderError.ConfigureEVR, e);
            }
        }
Esempio n. 6
0
        private void InitVideoWindow(IntPtr handle)
        {
            int hr = 0;

            if (!_isInit)
            {
                _isInit = true;

                if (_vw != null)
                {
                    hr = _vw.put_Owner(handle);
                    if (hr != 0)
                    {
                        return;
                    }

                    hr = _vw.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren);
                    _vw.put_MessageDrain(handle);
                    if (hr != 0)
                    {
                        return;
                    }
                }
                else if (_evr != null)
                {
                    if (!_delayedInit)
                    {
                        try
                        {
                            _evr.SetVideoWindow(handle);
                        }
                        catch (Exception ex)
                        {
                            _isInit      = false;
                            _delayedInit = true;
                        }
                    }
                }
            }
            OnResize(new EventArgs());
        }
Esempio n. 7
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();
        }
Esempio n. 8
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();
            }
        }
Esempio n. 9
0
        private void PlayMovieInWindow(string filename)
        {
            if (filename == string.Empty) return;

            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.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(-(int)(10000 - Math.Pow(Settings.VolumeLevel, 1.0 / 5) * 10000)); //Громкость для ДиректШоу

            // Is this an audio-only file (no video component)?
            CheckIsAudioOnly();
            if (!this.isAudioOnly)
            {
                //Определяем аспект, если он нам не известен
                if (in_ar == 0)
                {
                    MediaInfoWrapper media = new MediaInfoWrapper();
                    media.Open(filepath);
                    in_ar = media.Aspect;
                    media.Close();
                }

                if (videoWindow != null)
                {
                    // Setup the video window
                    hr = this.videoWindow.put_Owner(this.source.Handle);
                    DsError.ThrowExceptionForHR(hr);

                    hr = this.videoWindow.put_WindowStyle(DirectShowLib.WindowStyle.Child | DirectShowLib.WindowStyle.ClipSiblings |
                        DirectShowLib.WindowStyle.ClipChildren);
                    DsError.ThrowExceptionForHR(hr);
                }

                MoveVideoWindow();
            }
            else
            {
                if (VHost != null)
                {
                    VHost.Dispose();
                    VHost = null;
                    VHandle = IntPtr.Zero;
                    VHostElement.Child = null;
                }
            }

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

            this.Focus();

            // Run the graph to play the media file
            hr = this.mediaControl.Run();
            DsError.ThrowExceptionForHR(hr);

            this.currentState = PlayState.Running;
            SetPauseIcon();

            double duration = 0.0;
            hr = mediaPosition.get_Duration(out duration);
            DsError.ThrowExceptionForHR(hr);
            slider_pos.Maximum = duration;

            //Запускаем таймер обновления позиции
            if (timer != null) timer.Start();
        }
Esempio n. 10
0
 private void ConfigureEVR()
 {
     baseFilter = (IBaseFilter)new EnhancedVideoRenderer();
     IEVRFilterConfig filterConfig = (IEVRFilterConfig)baseFilter;
     filterConfig.SetNumberOfStreams(1);
     object o;
     ((IMFGetService)baseFilter).GetService(MR_VIDEO_RENDER_SERVICE, IID_IMFVideoDisplayControl, out o);
     EVRCtrl = (IMFVideoDisplayControl)o;
     EVRCtrl.SetVideoWindow(winHandle);
     EVRCtrl.SetAspectRatioMode(1);
     Form1_ResizeMove(null, null);
     graphBuilder.AddFilter(baseFilter, "Enhanced Video Renderer");
 }