Пример #1
0
        /// <summary>
        /// Resize video
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public int ResizeVideo(short width, short height)
        {
            TRACE(string.Format("ResizeVideo: {0}x{1}", width, height));

            int hr = S_Ok;

            if (m_pVideoDisplay != null)
            {
                try
                {
                    MFRect rcDest = new MFRect();
                    MFVideoNormalizedRect nRect = new MFVideoNormalizedRect();

                    nRect.left    = 0;
                    nRect.right   = 1;
                    nRect.top     = 0;
                    nRect.bottom  = 1;
                    rcDest.left   = 0;
                    rcDest.top    = 0;
                    rcDest.right  = width;
                    rcDest.bottom = height;

                    m_pVideoDisplay.SetVideoPosition(nRect, rcDest);
                }
                catch (Exception e)
                {
                    hr = Marshal.GetHRForException(e);
                }
            }

            return(hr);
        }
Пример #2
0
        /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
        /// <summary>
        /// Handle size changed events on this control
        /// </summary>
        /// <param name="errMsg">the error message</param>
        /// <param name="ex">the exception. Can be null</param>
        /// <history>
        ///    01 Nov 18  Cynic - Originally Written
        /// </history>
        private void ctlTantaEVRStreamDisplay_SizeChanged(object sender, EventArgs e)
        {
            LogMessage("ctlTantaEVRStreamDisplay_SizeChanged");

            HResult hr;

            if (evrVideoDisplay == null)
            {
                return;
            }

            try
            {
                // we are going to use the size changed event to reset the size of the video on the display.
                // This is controlled by two windows.

                // The source window determines which portion of the video is displayed. It is specified in
                // normalized coordinates. In other words, a value between 0 and 1. To display the entire video
                // image we would set the source rectangle to { 0, 0, 1, 1}. To display the bottom right quarter
                // we would set it to { 0.75f, 0.75f, 1, 1}. The default source rectangle is { 0, 0, 1, 1}.

                // The destination rectangle defines a rectangle within the clipping window (the video surface) where the video appears.
                // in this control this is the surface of a child panel control. This values is specified in pixels, relative to
                // the client area of the control. To fill the entire control, set the destination rectangle to { 0, 0, width, height},
                // where width and height are dimensions of the window client area.

                MFRect destinationRect           = new MFRect();
                MFVideoNormalizedRect sourceRect = new MFVideoNormalizedRect();

                // populate a MFVideoNormalizedRect structure that specifies the source rectangle.
                // This parameter can be NULL. If this parameter is NULL, the source rectangle does not change.
                sourceRect.left   = 0;
                sourceRect.right  = 1;
                sourceRect.top    = 0;
                sourceRect.bottom = 1;

                // populate the destination rectangle. This parameter can be NULL. If this parameter is NULL,
                // the destination rectangle does not change.
                destinationRect.left   = 0;
                destinationRect.top    = 0;
                destinationRect.right  = panelDisplayPanel.Width;
                destinationRect.bottom = panelDisplayPanel.Height;

                // now set the video display coordinates
                hr = evrVideoDisplay.SetVideoPosition(sourceRect, destinationRect);
                if (hr != HResult.S_OK)
                {
                    throw new Exception("ctlTantaEVRStreamDisplay_SizeChanged failed. Err=" + hr.ToString());
                }
            }
            catch (Exception ex)
            {
                LogMessage("ctlTantaEVRStreamDisplay_SizeChanged failed exception happened. ex=" + ex.Message);
                //        NotifyPlayerErrored(ex.Message, ex);
            }
        }
Пример #3
0
 public override void SetVideoPosition(GDI.RECT rcSrc, GDI.RECT rcDest)
 {
     // in EVR default source rectangle is {0.0, 0.0, 1.0, 1.0}, these are so-called normalized coordinates
     // however VMR, VMR9 and PVP consider the source rectangle as the video size
     // so we will just pass the default one to display the whole video frame
     // When we set video frame to be less than our windows EVR starts flickering in the surrounding areas, looks like some old content from
     // back buffers is being drawn
     // To overcme this issue we set our media window (nwnd) to be of the size of the video we want to show, in other words EVR should paint the whole window area
     // EVR's default destination rectangle is {0, 0, 0, 0} so we need to adjust it to {0, 0, width, height}
     _rcDest.right  = rcDest.right - rcDest.left;
     _rcDest.bottom = rcDest.bottom - rcDest.top;
     _pMFVideoDisplayControl.SetVideoPosition(ref _rcSrc, ref _rcDest);
 }
Пример #4
0
        private void FillWindow()
        {
            if (pDisplay == null)
            {
                return;
            }

            IMFVideoDisplayControl mfVideoDisplayControl = pDisplay;
            Rectangle r = panel.ClientRectangle;

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

            mfVideoDisplayControl.SetVideoPosition(null, rc);
        }
Пример #5
0
        void VideoInternalWindow_Resize(object sender, EventArgs e)
        {
            int top    = 0;
            int left   = 0;
            int width  = this.Width;
            int height = this.Height;

            if (_detachedWindow != null)
            {
                top    = _detachedWindow.ClientRectangle.Top;
                left   = _detachedWindow.ClientRectangle.Left;
                width  = _detachedWindow.ClientRectangle.Width;
                height = _detachedWindow.ClientRectangle.Height;
            }

            if (_isInit)
            {
                if (_vw != null)
                {
                    _vw.SetWindowPosition(top, left, width, height);
                }
                else if (_evr != null & !_delayedInit)
                {
                    try
                    {
                        MFRect rcDest = new MFRect();
                        MFVideoNormalizedRect nRect = new MFVideoNormalizedRect();

                        nRect.left    = 0;
                        nRect.right   = 1;
                        nRect.top     = 0;
                        nRect.bottom  = 1;
                        rcDest.left   = top;
                        rcDest.top    = left;
                        rcDest.right  = width;
                        rcDest.bottom = height;

                        _evr.SetVideoPosition(nRect, rcDest);
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        MessageBox.Show(ex.Message, "Failed to set EVR Window Position");
#endif
                    }
                }
            }
        }
Пример #6
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;
        }
Пример #7
0
        public int InitializeMedia(string MediaFile, int dwrate, float dwvolume, bool IsFullScreen)
        {
            int hr;

            MFStartup(MF_VERSION, MFSTARTUP_FULL);
            MFCreateMediaSession(IntPtr.Zero, out mediaSession);

            MFCreateTopology(out IMFTopology topo);
            MFCreateSourceResolver(out IMFSourceResolver resolver);
            IUnknown unknown;

            try
            {
                resolver.CreateObjectFromURL(MediaFile, MF_RESOLUTION_MEDIASOURCE | MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE,
                                             null, out uint objtype, out unknown);
            }
            catch
            {
                MessageBox.Show("不支持的媒体格式。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(0);
            }
            IMFMediaSource source = unknown as IMFMediaSource;

            source.CreatePresentationDescriptor(out IMFPresentationDescriptor descriptor);
            if (MFRequireProtectedEnvironment(descriptor) == 0)
            {
                MessageBox.Show("媒体受保护,无法播放。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(0);
            }
            descriptor.GetStreamDescriptorCount(out uint sdcount);
            for (uint i = 0; i < sdcount; i++)
            {
                descriptor.GetStreamDescriptorByIndex(i, out bool IsSelected, out IMFStreamDescriptor sd);
                if (!IsSelected)
                {
                    descriptor.SelectStream(i);
                }
                sd.GetMediaTypeHandler(out IMFMediaTypeHandler typeHandler);
                typeHandler.GetMajorType(out Guid streamtype);
                IMFActivate renderer;
                if (streamtype == MFMediaType_Audio)
                {
                    hr = MFCreateAudioRendererActivate(out renderer);
                }
                else if (streamtype == MFMediaType_Video)
                {
                    hr       = MFCreateVideoRendererActivate(VideoWnd.Handle, out renderer);
                    HasVideo = true;
                }
                else
                {
                    MessageBox.Show("不支持的媒体格式。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(0);
                }
                hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, out IMFTopologyNode sourcenode);
                sourcenode.SetUnknown(MF_TOPONODE_SOURCE, source as IUnknown);
                sourcenode.SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, descriptor as IUnknown);
                sourcenode.SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, sd as IUnknown);
                topo.AddNode(sourcenode);
                MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, out IMFTopologyNode outputnode);
                outputnode.SetObject(renderer as IUnknown);
                topo.AddNode(outputnode);
                outputnode.SetUINT32(MF_TOPONODE_NOSHUTDOWN_ON_REMOVE, 0);
                hr = sourcenode.ConnectOutput(0, outputnode, 0);
            }
            mediaSession.SetTopology(0, topo);
            Rate              = dwrate;
            Volume            = dwvolume;
            this.IsFullScreen = IsFullScreen;
            uint eventtype = 0;

            while (eventtype != MESessionTopologyStatus)
            {
                mediaSession.GetEvent(0, out IMFMediaEvent mediaevent);
                mediaevent.GetType(out eventtype);
                mediaevent = null;
            }
            Guid guid_ratecontrol = typeof(IMFRateControl).GUID;

            MFGetService(mediaSession as IUnknown, ref MF_RATE_CONTROL_SERVICE, ref guid_ratecontrol, out IUnknown _ratecontrol);
            IMFRateControl ratecontrol = _ratecontrol as IMFRateControl;

            hr = ratecontrol.SetRate(false, Rate >= 0 ? Rate * 7 / 10 + 1 : 1 / (1 + Rate / -10 * 7));
            try
            {
                Guid guid_volume      = typeof(IMFStreamAudioVolume).GUID;
                Guid guid_audiopolicy = typeof(IMFAudioPolicy).GUID;
                hr = MFGetService(mediaSession as IUnknown, ref MR_STREAM_VOLUME_SERVICE, ref guid_volume, out IUnknown _volume);
                hr = MFGetService(mediaSession as IUnknown, ref MR_AUDIO_POLICY_SERVICE, ref guid_audiopolicy, out IUnknown _policy);
                IMFStreamAudioVolume volumecontrol = _volume as IMFStreamAudioVolume;
                IMFAudioPolicy       policy        = _policy as IMFAudioPolicy;
                volumecontrol.GetChannelCount(out uint channelcount);
                for (uint c = 0; c < channelcount; c++)
                {
                    volumecontrol.SetChannelVolume(c, Volume);
                }
                policy.SetDisplayName(" ");
            }
            catch
            {
            }
            try
            {
                Guid guid_videocontrol = typeof(IMFVideoDisplayControl).GUID;
                hr = MFGetService(mediaSession as IUnknown, ref MR_VIDEO_RENDER_SERVICE, ref guid_videocontrol, out IUnknown _videocontrol);
                IMFVideoDisplayControl videocontrol = _videocontrol as IMFVideoDisplayControl;
                VideoWnd.videocontrol = videocontrol;
                if (IsFullScreen)
                {
                    VideoWnd.Top    = 0;
                    VideoWnd.Left   = 0;
                    VideoWnd.Width  = (int)System.Windows.SystemParameters.PrimaryScreenWidth;
                    VideoWnd.Height = (int)System.Windows.SystemParameters.PrimaryScreenHeight;
                }
                Rectangle videopos = new Rectangle(0, 0, VideoWnd.Width, VideoWnd.Height);
                videocontrol.SetVideoPosition(null, ref videopos);
            }
            catch
            {
            }
            hr = mediaSession.BeginGetEvent((IMFAsyncCallback)this, null);
            return(1);
        }
Пример #8
0
        private void SetVideoPositions()
        {
            var hiddenWindowContentSize = _hiddenWindow.ContentPixelSize;

            var screenWidth  = Convert.ToInt32(Math.Round(hiddenWindowContentSize.Width));
            var screenHeight = Convert.ToInt32(Math.Round(hiddenWindowContentSize.Height));

            _logger.Info("window content width: {0}, window height: {1}", screenWidth, screenHeight);

            // Set the display position to the entire window.
            var rc = new MFRect(0, 0, screenWidth, screenHeight);

            _mPDisplay.SetVideoPosition(null, rc);
            //_mPDisplay.SetFullscreen(true);

            // Get Aspect Ratio
            int aspectX;
            int aspectY;

            decimal heightAsPercentOfWidth = 0;

            var basicVideo2 = (IBasicVideo2)m_graph;

            basicVideo2.GetPreferredAspectRatio(out aspectX, out aspectY);

            var sourceHeight = 0;
            var sourceWidth  = 0;

            _basicVideo.GetVideoSize(out sourceWidth, out sourceHeight);

            if (aspectX == 0 || aspectY == 0 || sourceWidth > 0 || sourceHeight > 0)
            {
                aspectX = sourceWidth;
                aspectY = sourceHeight;
            }

            if (aspectX > 0 && aspectY > 0)
            {
                heightAsPercentOfWidth = decimal.Divide(aspectY, aspectX);
            }

            // Adjust Video Size
            var iAdjustedHeight = 0;

            if (aspectX > 0 && aspectY > 0)
            {
                var adjustedHeight = Convert.ToDouble(heightAsPercentOfWidth * screenWidth);
                iAdjustedHeight = Convert.ToInt32(Math.Round(adjustedHeight));
            }

            //SET MADVR WINDOW TO FULL SCREEN AND SET POSITION
            if (screenHeight >= iAdjustedHeight && iAdjustedHeight > 0)
            {
                double totalMargin = (screenHeight - iAdjustedHeight);
                var    topMargin   = Convert.ToInt32(Math.Round(totalMargin / 2));

                _basicVideo.SetDestinationPosition(0, topMargin, screenWidth, iAdjustedHeight);
            }
            else if (screenHeight < iAdjustedHeight && iAdjustedHeight > 0)
            {
                var adjustedWidth = Convert.ToDouble(screenHeight / heightAsPercentOfWidth);

                var iAdjustedWidth = Convert.ToInt32(Math.Round(adjustedWidth));

                if (iAdjustedWidth == 1919)
                {
                    iAdjustedWidth = 1920;
                }

                double totalMargin = (screenWidth - iAdjustedWidth);
                var    leftMargin  = Convert.ToInt32(Math.Round(totalMargin / 2));

                _basicVideo.SetDestinationPosition(leftMargin, 0, iAdjustedWidth, screenHeight);
            }
            _videoWindow.SetWindowPosition(0, 0, screenWidth, screenHeight);
        }
Пример #9
0
        public void InitializeMedia(string MediaFile, int dwrate, float dwvolume)
        {
            int hr;

            MFStartup(MF_VERSION, MFSTARTUP_FULL);
            MFCreateMediaSession(IntPtr.Zero, out IMFMediaSession mediaSession);
            MFCreateTopology(out IMFTopology topo);
            MFCreateSourceResolver(out IMFSourceResolver resolver);
            IUnknown unknown;

            try
            {
                resolver.CreateObjectFromURL(MediaFile, MF_RESOLUTION_MEDIASOURCE | MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE,
                                             null, out uint objtype, out unknown);
            }
            catch
            {
                MessageBox.Show("不支持的媒体格式。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            IMFMediaSource source = unknown as IMFMediaSource;

            source.CreatePresentationDescriptor(out IMFPresentationDescriptor descriptor);
            if (MFRequireProtectedEnvironment(descriptor) == 0)
            {
                MessageBox.Show("媒体受保护,无法播放。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            descriptor.GetStreamDescriptorCount(out uint sdcount);
            for (uint i = 0; i < sdcount; i++)
            {
                descriptor.GetStreamDescriptorByIndex(i, out bool IsSelected, out IMFStreamDescriptor sd);
                if (!IsSelected)
                {
                    descriptor.SelectStream(i);
                }
                sd.GetMediaTypeHandler(out IMFMediaTypeHandler typeHandler);
                typeHandler.GetMajorType(out Guid streamtype);
                IMFActivate renderer;
                if (streamtype == MFMediaType_Audio)
                {
                    hr = MFCreateAudioRendererActivate(out renderer);
                }
                else if (streamtype == MFMediaType_Video)
                {
                    hr       = MFCreateVideoRendererActivate(host.Handle, out renderer);
                    hasvideo = true;
                }
                else
                {
                    continue;
                }
                hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, out IMFTopologyNode sourcenode);
                sourcenode.SetUnknown(MF_TOPONODE_SOURCE, source as IUnknown);
                sourcenode.SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, descriptor as IUnknown);
                sourcenode.SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, sd as IUnknown);
                topo.AddNode(sourcenode);
                MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, out IMFTopologyNode outputnode);
                outputnode.SetObject(renderer as IUnknown);
                topo.AddNode(outputnode);
                hr = sourcenode.ConnectOutput(0, outputnode, 0);
            }
            mediaSession.SetTopology(0, topo);
            Hide();
            uint eventtype = 0;

            while (eventtype != MESessionTopologyStatus)
            {
                mediaSession.GetEvent(0, out IMFMediaEvent mediaevent);
                mediaevent.GetType(out eventtype);
                mediaevent = null;
            }
            Guid guid_ratecontrol = typeof(IMFRateControl).GUID;

            MFGetService(mediaSession as IUnknown, ref MF_RATE_CONTROL_SERVICE, ref guid_ratecontrol, out IUnknown _ratecontrol);
            IMFRateControl ratecontrol = _ratecontrol as IMFRateControl;

            hr = ratecontrol.SetRate(false, dwrate >= 0 ? dwrate * 7 / 10 + 1 : 1 / (1 + dwrate / -10 * 7));
            try
            {
                Guid guid_audiopolicy = typeof(IMFAudioPolicy).GUID;
                hr = MFGetService(mediaSession as IUnknown, ref MR_AUDIO_POLICY_SERVICE, ref guid_audiopolicy, out IUnknown _policy);
                IMFAudioPolicy policy = _policy as IMFAudioPolicy;
                policy.SetDisplayName(" ");
                playvolume = dwvolume;
            }
            catch
            {
            }
            try
            {
                Guid guid_videocontrol = typeof(IMFVideoDisplayControl).GUID;
                hr = MFGetService(mediaSession as IUnknown, ref MR_VIDEO_RENDER_SERVICE, ref guid_videocontrol, out IUnknown _videocontrol);
                IMFVideoDisplayControl videocontrol = _videocontrol as IMFVideoDisplayControl;
                if (FullScreen.Checked)
                {
                    host.Top    = 0;
                    host.Left   = 0;
                    host.Width  = (int)System.Windows.SystemParameters.PrimaryScreenWidth;
                    host.Height = (int)System.Windows.SystemParameters.PrimaryScreenHeight;
                }
                Rectangle videopos = new Rectangle(0, 0, host.Width, host.Height);
                host.videocontrol = videocontrol;
                videocontrol.SetVideoPosition(null, ref videopos);
            }
            catch
            {
            }
            state = "Prepared";
            while (true)
            {
                if (state == "Playing")
                {
                    eventtype = 0;
                    PropVariant prop = new PropVariant()
                    {
                        vt          = (ushort)VarEnum.VT_I8,
                        unionmember = 0,
                    };
                    #region mediasession
                    if (hasvideo)
                    {
                        host.Show();
                    }
                    preventthread = new Thread(() => {
                        while (true)
                        {
                            if (state == "Playing")
                            {
                                while (state == "Playing")
                                {
                                    if (hasvideo)
                                    {
                                        host.BringToFront();
                                    }
                                    SetAppAndSystemVolume(playvolume, false);
                                }
                            }
                        }
                    });
                    preventthread.Start();
                    hr = mediaSession.Start(Guid.Empty, prop);
                    while (eventtype != MESessionEnded)
                    {
                        hr = mediaSession.GetEvent(1, out IMFMediaEvent mediaevent);
                        if (hr == 0 && mediaevent != null)
                        {
                            mediaevent.GetType(out eventtype);
                            mediaevent = null;
                        }
                        Application.DoEvents();
                    }
                    host.Hide();
                    state = "Ended";
                    #endregion
                }
            }
        }