protected virtual void DoStopInternal(object state)
        {
            try
            {
                //ResetVolumeLevels();
#if HAVE_SAMPLES
                ReleaseAudioSampleGrabber();
#endif

                if (mediaControl != null)
                {
                    mediaControl.Stop();

                    mediaControl  = null;
                    mediaPosition = null;
                    videoWindow   = null;
                    basicVideo    = null;
                    basicAudio    = null;
                    mediaEvent    = null;
                }

                GC.Collect();
            }
            catch (Exception ex)
            {
                // This is running on other thread than the DSRenderer,
                // so its exceptions are not caught in MediaRenderer
                Logger.LogException(ex);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Open the file in <see cref="FilePath"/> and load it.
        /// </summary>
        private void OpenMediaFile()
        {
            ClosePlayer();
            int hr = 0;

            this.graphBuilder = (IGraphBuilder) new FilterGraph();
            hr = graphBuilder.RenderFile(this.FilePath, null);
            DsError.ThrowExceptionForHR(hr);
            this.mediaControl  = (IMediaControl)this.graphBuilder;
            this.mediaEventEx  = (IMediaEventEx)this.graphBuilder;
            this.mediaSeeking  = (IMediaSeeking)this.graphBuilder;
            this.mediaPosition = (IMediaPosition)this.graphBuilder;

            this.videoWindow = this.graphBuilder as IVideoWindow;
            this.basicVideo  = this.graphBuilder as IBasicVideo;
            int x, y;

            this.basicVideo.GetVideoSize(out x, out y);
            this.VideoSize  = new Size(x, y);
            this.basicAudio = (IBasicAudio)this.graphBuilder;
            hr = this.mediaEventEx.SetNotifyWindow(notifyTarget, WMGraphNotify, IntPtr.Zero);
            DsError.ThrowExceptionForHR(hr);
            hr = this.videoWindow.put_Owner(owner);
            DsError.ThrowExceptionForHR(hr);
            hr = this.videoWindow.put_WindowStyle(WindowStyle.Child |
                                                  WindowStyle.ClipSiblings | WindowStyle.ClipChildren);
            DsError.ThrowExceptionForHR(hr);
            videoWindow.SetWindowPosition(0, 0, Control.FromHandle(this.owner).Width, Control.FromHandle(this.owner).Height);
            double time;

            mediaPosition.get_Duration(out time);
            this.Length = (int)(time * 1000);

            this.State = PlayState.Opened;
        }
Exemplo n.º 3
0
        public void ResizeWindowToVideo()
        {
            IVideoWindow pVW = m_pRenderGraph as IVideoWindow;
            IBasicVideo  pBV = m_pRenderGraph as IBasicVideo;

            if ((pVW != null) && (pBV != null))
            {
                // size of new video
                int cx, cy;
                pBV.GetVideoSize(out cx, out cy);
                DsRect rcVideo = new DsRect(0, 0, cx, cy);

                // adjust from client size to window size
                WindowStyle style;
                pVW.get_WindowStyle(out style);
                //AdjustWindowRect(rcVideo, style, false);

                // get current window top/left
                int    cxWindow, cyWindow;
                DsRect rc = new DsRect();
                pVW.GetWindowPosition(out rc.left, out rc.top, out cxWindow, out cyWindow);

                // reposition video window with old top/left position and new size
                pVW.SetWindowPosition(rc.left, rc.top, rcVideo.right - rcVideo.left, rcVideo.bottom - rcVideo.top);
            }
        }
Exemplo n.º 4
0
        /// <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);

                // Create the DirectShow filter graph manager
                fgm = new FilgraphManagerClass();
                IGraphBuilder iGB = (IGraphBuilder)fgm;
                rotID = FilterGraph.AddToRot((IGraphBuilder)fgm);

                IBaseFilter bfSource = RtpSourceClass.CreateInstance();
                ((MSR.LST.MDShow.Filters.IRtpSource)bfSource).Initialize(rtpStream);

                iGB.AddFilter(bfSource, "RtpSource");
                iGB.Render(Filter.GetPin(bfSource, _PinDirection.PINDIR_OUTPUT, Guid.Empty,
                                         Guid.Empty, false, 0));

                DisableDXVA(fgm);

                // Render the video inside of the form
                iVW = (IVideoWindow)fgm;

                // Get the correct ratio to use for the video stretching
                //  I would expect the fgm to always be castable to this, but I simply don't trust DShow
                IBasicVideo iBV = fgm as IBasicVideo;
                if (iBV != null)
                {
                    int vidWidth, vidHeight;
                    iBV.GetVideoSize(out vidWidth, out vidHeight);
                    vidSrcRatio = (double)vidHeight / (double)vidWidth;
                }

                // Remove the border from the default DShow renderer UI
                int ws = WindowStyle;
                ws          = ws & ~(0x00800000); // Remove WS_BORDER
                ws          = ws & ~(0x00400000); // Remove WS_DLGFRAME
                WindowStyle = ws;

                iVW = null;

                uiState &= ~(int)FAudioVideo.UIState.RemoteVideoStopped;

                if (form != null)
                {
                    ((FAudioVideo)form).UpdateVideoUI(uiState);
                }

                // FirstFrameReceived interprets fgmState as the *desired* state for the fgm
                // Because ResumePlayingVideo 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;
                    ResumePlayingVideo();
                }
            }
        }
Exemplo n.º 5
0
        // Starts playing a new cinematic
        public void PlayCinematic(string file, int x, int y, int w, int h)
        {
            // Lame bugfix: DirectShow and Fullscreen doesnt like eachother
            if (CVars.Instance.Get("r_fs", "0", CVarFlags.ARCHIVE).Integer == 1)
            {
                if (AlterGameState)
                {
                    playing = true;
                    StopCinematic();
                }
                return;
            }

            // Check if file exists
            if (FileCache.Instance.Contains(file))
                file = FileCache.Instance.GetFile(file).FullName;
            else
            {
                if (AlterGameState)
                {
                    playing = true;
                    StopCinematic();
                }
                Common.Instance.WriteLine("PlayCinematic: Could not find video: {0}", file);
                return;
            }

            // Have the graph builder construct its the appropriate graph automatically
            this.graphBuilder = (IGraphBuilder)new FilterGraph();
            int hr = graphBuilder.RenderFile(file, null);
            DsError.ThrowExceptionForHR(hr);

            mediaControl = (IMediaControl)this.graphBuilder;
            mediaEventEx = (IMediaEventEx)this.graphBuilder;
            videoWindow = this.graphBuilder as IVideoWindow;
            basicVideo = this.graphBuilder as IBasicVideo;

            // Setup the video window
            hr = this.videoWindow.put_Owner(Renderer.Instance.form.Handle);
            DsError.ThrowExceptionForHR(hr);
            hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren);
            DsError.ThrowExceptionForHR(hr);

            // Set the video size
            //int lWidth, lHeight;
            //hr = this.basicVideo.GetVideoSize(out lWidth, out lHeight);
            hr = this.videoWindow.SetWindowPosition(x, y, w, h);
            videoWindow.put_FullScreenMode((CVars.Instance.Get("r_fs", "0", CVarFlags.ARCHIVE).Integer == 1) ? OABool.True : OABool.False);
            DsError.ThrowExceptionForHR(hr);

            // Run the graph to play the media file
            hr = this.mediaControl.Run();
            DsError.ThrowExceptionForHR(hr);
            playing = true;
            if (AlterGameState)
                Client.Instance.state = CubeHags.common.ConnectState.CINEMATIC;
            Common.Instance.WriteLine("Playing cinematic: {0}", file);

            EventCode code;
        }
Exemplo n.º 6
0
        // Configure the video to fit in the provided window (if any)
        private void ConfigureVideo(IntPtr hwnd)
        {
            int hr;

            if (hwnd != IntPtr.Zero)
            {
                int         cx, cy;
                IBasicVideo pBV = (IBasicVideo)m_pSourceGraph;

                hr = pBV.GetVideoSize(out cx, out cy);
                DsError.ThrowExceptionForHR(hr);

                // reparent playback window
                IVideoWindow pVW = (IVideoWindow)m_pSourceGraph;

                hr = pVW.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren);
                DsError.ThrowExceptionForHR(hr);

                hr = pVW.put_Owner(hwnd);
                DsError.ThrowExceptionForHR(hr);

                hr = pVW.SetWindowPosition(1, 13, cx - 7, cy);
                DsError.ThrowExceptionForHR(hr);
            }
        }
Exemplo n.º 7
0
        public void Play(Resource resource)
        {
            // Have the graph builder construct its the appropriate graph automatically
            if (this.currentMediaFile.Equals(resource.FullName))
            {
                return;
            }
            this.graphBuilder = (IGraphBuilder) new FilterGraph();
            hr = this.graphBuilder.RenderFile(resource.FullName, null);
            DsError.ThrowExceptionForHR(hr);
            // QueryInterface for DirectShow interfaces
            this.mediaControl  = (IMediaControl)this.graphBuilder;
            this.mediaEventEx  = (IMediaEventEx)this.graphBuilder;
            this.mediaSeeking  = (IMediaSeeking)this.graphBuilder;
            this.mediaPosition = (IMediaPosition)this.graphBuilder;

            // Query for video interfaces, which may not be relevant for audio files
            this.videoWindow = this.graphBuilder as IVideoWindow;
            this.basicVideo  = this.graphBuilder as IBasicVideo;

            // Query for audio interfaces, which may not be relevant for video-only files
            this.basicAudio = this.graphBuilder as IBasicAudio;
            this.MoveVideoWindow();
            this.mediaControl.Run();
            this.currentMediaFile = resource.FullName;
        }
Exemplo n.º 8
0
        private void btnSize_Click(object sender, EventArgs e)
        {
            if (null == m_fm)
            {
                return;
            }

            btnHalf.Checked     = false;
            btnOriginal.Checked = false;
            btnTwice.Checked    = false;
            (sender as ToolStripButton).Checked = true;

            try
            {
                IBasicVideo bv = m_fm as IBasicVideo;
                if (sender == btnHalf)
                {
                    int h = bv.SourceHeight / 2;
                    this.ClientSize = new Size(bv.SourceWidth / 2, h < ts.Height ? 1 : h - ts.Height);
                }
                else if (sender == btnOriginal)
                {
                    int h = bv.SourceHeight;
                    this.ClientSize = new Size(bv.SourceWidth, h < ts.Height ? 1 : h - ts.Height);
                }
                else if (sender == btnTwice)
                {
                    int h = bv.SourceHeight * 2;
                    this.ClientSize = new Size(bv.SourceWidth * 2, h < ts.Height ? 1 : h - ts.Height);
                }
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 9
0
        //Ctrl'event
        private void btnPlay_Click(object sender, EventArgs e)
        {
            int hr = 0;

            if (this.graphBuilder == null)
            {
                string filename = txtPath.Text;
                this.graphBuilder = (IGraphBuilder) new FilterGraph();

                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;

                hr = this.mediaEventEx.SetNotifyWindow(this.Handle, WMGraphNotify, IntPtr.Zero);
                DsError.ThrowExceptionForHR(hr);
                //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);

                this.Focus();

                hr = InitVideoWindow(1, 1);
                DsError.ThrowExceptionForHR(hr);

                double time;
                mediaPosition.get_Duration(out time);
                trackBar1.SetRange(0, (int)time);
                //create a new Thread
                t = new Thread(new ThreadStart(updateTimeBarThread));

                if (btnPlay.Text.Equals("Play"))
                {
                    hr = this.mediaControl.Run();
                    DsError.ThrowExceptionForHR(hr);
                    btnPlay.Text = "Pause";
                }
                else
                {
                    hr = this.mediaControl.Pause();
                    DsError.ThrowExceptionForHR(hr);
                    btnPlay.Text = "Play";
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 获取视频流相关信息
        /// </summary>
        private void Grab()
        {
            try
            {
                mediaInfo = new MediaInfo();
                double fps, length;
                mediaDet = (IMediaDet) new MediaDet();
                mediaDet.put_Filename(fileName);

                mediaDet.get_StreamLength(out length);

                graphBuilder  = (IGraphBuilder) new FilterGraph();
                sampleGrabber = (ISampleGrabber) new SampleGrabber();
                ConfigSampleGrabber(this.sampleGrabber);
                this.graphBuilder.AddFilter((IBaseFilter)sampleGrabber, "SampleGrabber");
                DsError.ThrowExceptionForHR(this.graphBuilder.RenderFile(fileName, null));
                basicVideo = this.graphBuilder as IBasicVideo;
                fps        = getFramePerSecond();
                AMMediaType media = new AMMediaType();

                this.sampleGrabber.GetConnectedMediaType(media);
                if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero))
                {
                    throw new Exception("Format type incorrect");
                }

                double interval = 1 / fps;

                int videoWidth, videoHeight, videoStride;
                this.basicVideo.GetVideoSize(out videoWidth, out videoHeight);
                VideoInfoHeader videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader));
                videoStride = videoWidth * (videoInfoHeader.BmiHeader.BitCount / 8);
                this.mediaInfo.MediaWidth    = videoWidth;
                this.mediaInfo.MediaHeight   = videoHeight;
                this.mediaInfo.MediaStride   = videoStride;
                this.mediaInfo.MediaBitCount = videoInfoHeader.BmiHeader.BitCount;
                this.mediaInfo.FPS           = fps;
                this.mediaInfo.Duration      = length;
                DsUtils.FreeAMMediaType(media);
                media = null;
                int index = 0;
                for (double i = 0; i < length; i = i + interval)
                {
                    SnapShot(index);
                    if (ReportProgressHandler != null)
                    {
                        ReportProgressHandler(index);
                    }
                    index++;
                }
                //var v = frames.Count;
            }
            catch (Exception ee)
            {
            }
        }
        public VideoFileInfo QueryVideoMediaInfo(string path)
        {
            VideoFileInfo vfi = null;

            DvdMedia dvdDrive = DvdMedia.FromPath(path);

            if (dvdDrive != null)
            {
                vfi = dvdDrive.VideoDvdInformation;
            }
            else
            {
                vfi = new VideoFileInfo(path, false);

                try
                {
                    if (vfi != null && vfi.IsValid)
                    {
                        Guid filterGraphGuid  = ProTONEConfig.FilterGraphGuid;
                        Type mediaControlType = Type.GetTypeFromCLSID(filterGraphGuid, true);

                        IMediaControl  mediaControl  = Activator.CreateInstance(mediaControlType) as IMediaControl;
                        IBasicAudio    basicAudio    = mediaControl as IBasicAudio;
                        IBasicVideo    basicVideo    = mediaControl as IBasicVideo;
                        IMediaPosition mediaPosition = mediaControl as IMediaPosition;

                        mediaControl.RenderFile(path);

                        double val = 0;
                        DsError.ThrowExceptionForHR(mediaPosition.get_Duration(out val));
                        vfi.Duration = TimeSpan.FromSeconds(val);

                        DsError.ThrowExceptionForHR(basicVideo.get_AvgTimePerFrame(out val));
                        vfi.FrameRate = new FrameRate(1f / val);

                        int h = 0, w = 0;
                        DsError.ThrowExceptionForHR(basicVideo.get_VideoHeight(out h));
                        DsError.ThrowExceptionForHR(basicVideo.get_VideoWidth(out w));
                        vfi.VideoSize = new VSize(w, h);

                        mediaControl.Stop();
                        mediaControl  = null;
                        mediaPosition = null;
                        basicVideo    = null;
                        basicAudio    = null;

                        GC.Collect();
                    }
                }
                catch
                {
                }
            }

            return(vfi);
        }
Exemplo n.º 12
0
        private void SetupDummyWindow()
        {
            Guid        CLSID_VideoMixingRenderer9 = new Guid("{51B4ABF3-748F-4E3B-A276-C828330E926A}"); //quartz.dll
            IBaseFilter pRenderer = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_VideoMixingRenderer9));

            m_FilterGraph.AddFilter(pRenderer, "Video Mixing Renderer 9");
            pRenderIn = DsFindPin.ByDirection(pRenderer, PinDirection.Input, 0);
            m_FilterGraph.Connect(pCaptureSampleOut, pRenderIn);
            ibv = pRenderer as IBasicVideo;
        }
Exemplo n.º 13
0
        private void Grab()
        {
            try
            {
                _mediaInfo = new MediaInfo();
                double fps, length;
                _mediaDet = (IMediaDet) new MediaDet();
                _mediaDet.put_Filename(_fileName);
                _mediaDet.get_FrameRate(out fps);
                _mediaDet.get_StreamLength(out length);

                _graphBuilder  = (IGraphBuilder) new FilterGraph();
                _sampleGrabber = (ISampleGrabber) new SampleGrabber();
                ConfigSampleGrabber(this._sampleGrabber, fps, length);
                this._graphBuilder.AddFilter((IBaseFilter)_sampleGrabber, "SampleGrabber");
                DsError.ThrowExceptionForHR(this._graphBuilder.RenderFile(_fileName, null));
                _basicVideo = this._graphBuilder as IBasicVideo;

                AMMediaType media = new AMMediaType();

                this._sampleGrabber.GetConnectedMediaType(media);
                if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero))
                {
                    throw new Exception("Format type incorrect");
                }

                double interval = 1 / fps;

                int videoWidth, videoHeight, videoStride;
                this._basicVideo.GetVideoSize(out videoWidth, out videoHeight);
                VideoInfoHeader videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader));
                videoStride                   = videoWidth * (videoInfoHeader.BmiHeader.BitCount / 8);
                this._mediaInfo.FPS           = fps;
                this._mediaInfo.Duration      = length;
                this._mediaInfo.MediaWidth    = videoWidth;
                this._mediaInfo.MediaHeight   = videoHeight;
                this._mediaInfo.MediaStride   = videoStride;
                this._mediaInfo.MediaBitCount = videoInfoHeader.BmiHeader.BitCount;
                DsUtils.FreeAMMediaType(media);
                media = null;

                for (double i = 0; i < length; i = i + interval)
                {
                    Bitmap bitmap = SnapShot(i);
                    _frames.Add(new Frames(i, bitmap, i.ToString()));
                    if (ReportProgressHandler != null)
                    {
                        ReportProgressHandler(i);
                    }
                }
            }
            catch (Exception ee)
            {
            }
        }
Exemplo n.º 14
0
        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;
        }
Exemplo n.º 15
0
        /// <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;
        }
        /// <summary>
        /// Call this method in order to capture a bitmap of the current video window
        /// TODO - hook up to a button click event
        /// TODO - give the user the ability to provide a file name
        /// </summary>
        ///
        /// <remarks>
        /// This is the layout in memory, because this is the layout we need
        /// on the disk.
        ///
        /// <-------------------------- ptrBlock ----------------------------->
        ///                    <------- ptrImg ------------------------------->
        /// | BitmapFileHeader | BitmapInfoHeader | bytes of DIB              |
        /// </remarks>
        private void TakeImage()
        {
            IBasicVideo iBV = (IBasicVideo)vcg.FilgraphManager;
            int         len = 0;

            // Determine byte count needed to store the Device Independent
            // Bitmap (DIB) by calling with a null-pointer
            iBV.GetCurrentImage(ref len, IntPtr.Zero);

            // Allocate bytes, plus room for a BitmapFileHeader
            int    sizeOfBFH = Marshal.SizeOf(typeof(BITMAPFILEHEADER));
            IntPtr ptrBlock  = Marshal.AllocCoTaskMem(len + sizeOfBFH);
            IntPtr ptrImg    = new IntPtr(ptrBlock.ToInt64() + sizeOfBFH);

            try
            {
                // Get the DIB
                iBV.GetCurrentImage(ref len, ptrImg);

                // Get a copy of the BITMAPINFOHEADER, to be used in the BITMAPFILEHEADER
                BITMAPINFOHEADER bmih = (BITMAPINFOHEADER)Marshal.PtrToStructure(
                    ptrImg, typeof(BITMAPINFOHEADER));

                // Create header for a file of type .bmp
                BITMAPFILEHEADER bfh = new BITMAPFILEHEADER();
                bfh.Type      = (UInt16)((((byte)'M') << 8) | ((byte)'B'));
                bfh.Size      = (uint)(len + sizeOfBFH);
                bfh.Reserved1 = 0;
                bfh.Reserved2 = 0;
                bfh.OffBits   = (uint)(sizeOfBFH + bmih.Size);

                // Copy the BFH into unmanaged memory, so that we can copy
                // everything into a managed byte array all at once
                Marshal.StructureToPtr(bfh, ptrBlock, false);

                // Pull it out of unmanaged memory into a managed byte[]
                byte[] img = new byte[len + sizeOfBFH];
                Marshal.Copy(ptrBlock, img, 0, len + sizeOfBFH);

                // Save the DIB to a file
                System.IO.File.WriteAllBytes("c:\\cxp.bmp", img);
            }
            finally
            {
                // Free the unmanaged memory
                if (ptrBlock != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(ptrBlock);
                }
            }
        }
Exemplo n.º 17
0
        /// <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();
        }
Exemplo n.º 18
0
        private void FrmVideo_Shown(object sender, EventArgs e)
        {
            if (null == m_fm)
            {
                this.Close();
                return;
            }

            try
            {
                IBasicVideo bv = m_fm as IBasicVideo;
                m_org_width  = bv.SourceWidth;
                m_org_height = bv.SourceHeight;
                int h = bv.SourceHeight;
                this.ClientSize = new Size(bv.SourceWidth, h < ts.Height ? 1 : h - ts.Height);

                this.SetBounds(
                    (Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                    (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2,
                    0, 0, BoundsSpecified.Location);

                const int WS_CHILD        = 0x40000000;
                const int WS_CLIPCHILDREN = 0x2000000;

                IVideoWindow vw = m_fm as IVideoWindow;
                vw.Owner       = pnVideo.Handle.ToInt32();
                vw.WindowStyle = WS_CHILD | WS_CLIPCHILDREN;
                vw.SetWindowPosition(
                    pnVideo.Left,
                    pnVideo.Top,
                    pnVideo.Width,
                    pnVideo.Height);

                //IMediaEventEx mee = m_fm as IMediaEventEx;
                //mee.SetNotifyWindow(this.Handle.ToInt32(), WM_GRAPHNOTIFY, 0);

                IMediaControl mc = m_fm as IMediaControl;
                mc.Run();
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 19
0
        public override void Play(bool bLoop, double from)
        {
            if (mediaControl == null)
            {
                return;
            }
            ((IBasicAudio)mediaControl).Volume = (int)(MusicData.Volume > 0 ? 2000 * Math.Log10(MusicData.Volume / 100) : -10000);
            realLoopStart = MusicData.LoopStart;
            realLoopEnd   = MusicData.LoopEnd > 0 ? MusicData.LoopEnd : ((IMediaPosition)mediaControl).Duration;
            ((IMediaPosition)mediaControl).Rate            = rate;
            ((IMediaPosition)mediaControl).CurrentPosition = from;
            if (typeof(IBasicVideo).IsInstanceOfType(mediaControl))
            {
                // TODO: 必要なら実装しよう(#11)
#pragma warning disable IDE0059 // 値の不必要な代入
                IBasicVideo v = (IBasicVideo)mediaControl;
#pragma warning restore IDE0059 // 値の不必要な代入
            }
            mediaControl.Run();
        }
Exemplo n.º 20
0
        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
            {
            }
        }
Exemplo n.º 21
0
        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;
                    iVW = null;
                    iBV = null;
                }
            }
        }
Exemplo n.º 22
0
 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);
     }
 }
Exemplo n.º 23
0
        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));
            }
        }
Exemplo n.º 24
0
        protected virtual HRESULT PreparePlayback()
        {
            m_MediaControl  = (IMediaControl)m_GraphBuilder;
            m_BasicVideo    = (IBasicVideo)m_GraphBuilder;
            m_MediaSeeking  = (IMediaSeeking)m_GraphBuilder;
            m_VideoWindow   = (IVideoWindow)m_GraphBuilder;
            m_MediaEventEx  = (IMediaEventEx)m_GraphBuilder;
            m_FrameStep     = (IVideoFrameStep)m_GraphBuilder;
            m_MediaPosition = (IMediaPosition)m_GraphBuilder;
            SettingUpVideoWindow();
            int hr = m_MediaEventEx.SetNotifyWindow(m_EventControl.Handle, WM_GRAPHNOTIFY, Marshal.GetIUnknownForObject(this));

            Debug.Assert(hr == 0);
            SetVolume(m_bMute ? -10000 : m_iVolume);
            if (m_dRate != 1.0)
            {
                m_MediaSeeking.SetRate(m_dRate);
                m_MediaSeeking.GetRate(out m_dRate);
            }
            OnPlaybackReady?.Invoke(this, EventArgs.Empty);
            return((HRESULT)hr);
        }
Exemplo n.º 25
0
        public void ResumePlayingVideo()
        {
            Debug.Assert(IsPlaying);

            lock (fgmLock)
            {
                if (fgmState != FilterGraph.State.Running)
                {
                    fgmState = FilterGraph.State.Running;

                    if (fgm != null)
                    {
                        // Due to some interesting bugs(?) in DShow, it is necessary for us to keep
                        // track of our state and re-initialize iBV and iVW
                        iBV              = (IBasicVideo)fgm;
                        iVW              = (IVideoWindow)fgm;
                        iVW.Owner        = videoWindowHandle.ToInt32();
                        iVW.MessageDrain = videoMessageDrainHandle.ToInt32();
                        iVW.Visible      = -1;

                        ResizeVideoStream(videoWindowHeight, videoWindowWidth);

                        // 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.LocalVideoPlayStopped;
                    ((FAudioVideo)form).UpdateVideoUI(uiState);
                }
            }
        }
Exemplo n.º 26
0
        public void StopPlayingVideo()
        {
            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();
                        }

                        // Due to some interesting bugs(?) in DShow, it is necessary for us to keep
                        // track of our state and re-initialize iBV and iVW
                        // We set the Owner to zero, otherwise when a window goes away and a new one
                        // takes its place we can't control it.
                        fgm.Stop();

                        if (iVW != null)
                        {
                            iVW.Visible = 0;
                            iVW.Owner   = 0;
                            iVW         = null;
                        }

                        iBV = null;
                    }

                    uiState |= (int)FAudioVideo.UIState.LocalVideoPlayStopped;
                    ((FAudioVideo)form).UpdateVideoUI(uiState);
                }
            }
        }
Exemplo n.º 27
0
        public void DoTests()
        {
            m_graphBuilder = BuildGraph(g_TestFile);
            m_ibv          = m_graphBuilder as IBasicVideo;

            try
            {
                TestAvgTime();
                TestBitErrorRate();
                TestBitRate();
                TestVideoDim();
                TestSourceLeft();
                TestSourceTop();
                TestSourceWidth();
                TestSourceHeight();
                TestDestinationWidth();
                TestDestinationLeft();
                TestDestinationTop();
                TestDestinationHeight();
                TestSourcePos();
                TestDestinationPos();
                TestGetImage();
                TestPalette();
            }
            finally
            {
                if (m_graphBuilder != null)
                {
                    Marshal.ReleaseComObject(m_graphBuilder);
                }

                m_graphBuilder = null;
                m_ibv          = null;
                m_dsrot.Dispose();
            }
        }
Exemplo n.º 28
0
        // Stops a running cinematic
        public void StopCinematic()
        {
            if (!playing)
                return;

            Common.Instance.WriteLine("Stopping cinematic...");

            // Stop DirectShow
            if (mediaControl != null)
            {
                // Stop playback
                mediaControl.Stop();
                // Remove overlay
                videoWindow.put_FullScreenMode(OABool.False);
                int hr = this.videoWindow.put_Visible(OABool.False);
                DsError.ThrowExceptionForHR(hr);
                hr = this.videoWindow.put_Owner(IntPtr.Zero);
                DsError.ThrowExceptionForHR(hr);
                // Clean up
                if (this.mediaEventEx != null)
                    this.mediaEventEx = null;
                if (this.mediaControl != null)
                    this.mediaControl = null;
                if (this.basicVideo != null)
                    this.basicVideo = null;
                if (this.videoWindow != null)
                    this.videoWindow = null;
                Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null;
            }

            // If cinematic alters gamestate, go ahead and do that..
            if (AlterGameState)
            {
                Client.Instance.state = CubeHags.common.ConnectState.DISCONNECTED;
                string s = CVars.Instance.VariableString("nextmap"); // next gamestate contained in nextmap
                if (s.Length > 0)
                {
                    Commands.Instance.ExecuteText(Commands.EXECTYPE.EXEC_APPEND, s+"\n");
                    CVars.Instance.Set("nextmap", "");
                }
                AlterGameState = false;
            }

            playing = false;
        }
Exemplo n.º 29
0
        protected override void Open_Call(string filename)
        {
            int hr = 0;

            graphBuilder = (IGraphBuilder) new FilterGraph();

            // Have the graph builder construct its the appropriate graph automatically
            hr = graphBuilder.RenderFile(filename, null);
            DsError.ThrowExceptionForHR(hr);
            /*
            try
            {
                hr = graphBuilder.RenderFile(filename, null);
                DsError.ThrowExceptionForHR(hr);
            }
            catch(Exception ex)
            {
                SystemMessage.Show(
                    Loc.T("Player.Message.CantOpenVideoFile") + Environment.NewLine+ Environment.NewLine +
                    "Exeption details :" + Environment.NewLine +
                     ex.Message + Environment.NewLine +
                     ex.Source
                    );
                return;
            }
            */
            // QueryInterface for DirectShow interfaces
            mediaControl = (IMediaControl) graphBuilder;
            mediaEventEx = (IMediaEventEx) graphBuilder;
            //mediaSeeking = (IMediaSeeking) graphBuilder;
            mediaPosition = (IMediaPosition) graphBuilder;

            // Query for video interfaces, which may not be relevant for audio files
            videoWindow = graphBuilder as IVideoWindow;
            basicVideo = graphBuilder as IBasicVideo;

            // Query for audio interfaces, which may not be relevant for video-only files
            basicAudio = graphBuilder as IBasicAudio;


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

            // Setup the video window
            hr = this.videoWindow.put_Owner(Handle);
            DsError.ThrowExceptionForHR(hr);

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

            try
            {
                Host_SizeChanged(null, null);
            }
            catch { }
            

            #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);

        }
Exemplo n.º 30
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();
        }
Exemplo n.º 31
0
        private void ClosePlayback()
        {
            int hr = 0;

            try
            {
                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
            {
            }
        }
Exemplo n.º 32
0
        public void openVid(string fileName)
        {
            if (!File.Exists(fileName))
            {
                errorMsg("El archivo '" + fileName + "' no existe.");
                videoPanel.Visible = false;
                isVideoLoaded = false;
                drawPositions();
                return;
            }

            if (VideoBoxType == PreviewType.AviSynth)
            {
                avsClip = null;
                //butPause.Enabled = true;
                //butPlayR.Enabled = true;
                //butPlay.Enabled = true;
                //butStop.Enabled = true;
                videoPictureBox.Visible = false;
                //closeVidDShow(); // añadido
            }

            if (mediaControl != null)
            {
                mediaControl.Stop();
                videoWindow.put_Visible(DirectShowLib.OABool.False);
                videoWindow.put_Owner(IntPtr.Zero);
            }

            // Dshow :~~

            graphBuilder = (IGraphBuilder)new FilterGraph();
            graphBuilder.RenderFile(fileName, null);
            mediaControl = (IMediaControl)graphBuilder;
            // mediaEventEx = (IMediaEventEx)this.graphBuilder;
            mediaSeeking = (IMediaSeeking)graphBuilder;
            mediaPosition = (IMediaPosition)graphBuilder;
            basicVideo = graphBuilder as IBasicVideo;
            videoWindow = graphBuilder as IVideoWindow;

            VideoBoxType = PreviewType.DirectShow;

            // sacando información

            int x, y; double atpf;
            basicVideo.GetVideoSize(out x, out y);
            if (x == 0 || y == 0)
            {
                errorMsg("No se puede abrir un vídeo sin dimensiones.");
                videoPanel.Visible = false;
                isVideoLoaded = false;
                drawPositions();
                return;
            }

            if (videoInfo == null) videoInfo = new VideoInfo(fileName);

            videoInfo.Resolution = new Size(x, y);

            basicVideo.get_AvgTimePerFrame(out atpf);
            videoInfo.FrameRate = Math.Round(1 / atpf, 3);

            //labelResFPS.Text = x.ToString() + "x" + y.ToString() + " @ " + videoInfo.FrameRate.ToString() + " fps";
            textResX.Text = x.ToString();
            textResY.Text = y.ToString();
            textFPS.Text = videoInfo.FrameRate.ToString();

            if (File.Exists(Application.StartupPath+"\\MediaInfo.dll") && File.Exists(Application.StartupPath+"\\MediaInfoWrapper.dll"))
            {
                treeView1.Enabled = true;
                try
                {
                    RetrieveMediaFileInfo(fileName);
                }
                catch { treeView1.Enabled = false; }
            }
            else treeView1.Enabled = false;

            if (x != 0)
            {
                vidScaleFactor.Enabled = true;

                try
                {
                    vidScaleFactor.Text = getFromConfigFile("mainW_Zoom");
                }
                catch
                {
                    vidScaleFactor.Text = "50%";
                };

                double p = double.Parse(vidScaleFactor.Text.Substring(0, vidScaleFactor.Text.IndexOf('%')));
                p = p / 100;

                int new_x = (int)(x * p);
                int new_y = (int)(y * p);

                videoWindow.put_Height(new_x);
                videoWindow.put_Width(new_y);
                videoWindow.put_Owner(videoPanel.Handle);
                videoPanel.Size = new System.Drawing.Size(new_x, new_y);
                videoWindow.SetWindowPosition(0, 0, videoPanel.Width, videoPanel.Height);
                videoWindow.put_WindowStyle(WindowStyle.Child);
                videoWindow.put_Visible(DirectShowLib.OABool.True);

            }
            else vidScaleFactor.Enabled = false;

            // timer
            actualizaFrames.Interval = 10;
            actualizaFrames.Enabled = true;

            //mediaControl.Run();
            drawPositions();

            framesFin.Enabled = true;
            buttonAddFrameInicio.Enabled = buttonAddFrameInicio.Visible = true;
            framesInicio.Enabled = true;
            buttonAddFrameFin.Enabled = buttonAddFrameFin.Visible = true;
            butClip.Enabled = false;

            mediaSeeking.SetTimeFormat(DirectShowLib.TimeFormat.Frame);

            videoInfo.FrameTotal = VideoUnitConversion.getTotal(mediaSeeking, videoInfo.FrameRate);
            seekBar.Maximum = FrameTotal;
            seekBar.TickFrequency = seekBar.Maximum / 10;

            // VFW ( __ SOLO AVIs __ )

            try
            {
                AVIFileWrapper.AVIFileInit();
                int aviFile = 0;
                IntPtr aviStream;
                int res = AVIFileWrapper.AVIFileOpen(ref aviFile, fileName, 0x20, 0);
                res = AVIFileWrapper.AVIFileGetStream(aviFile, out aviStream, 1935960438, 0);

                videoInfo.KeyFrames = new ArrayList();
                int nFrames = FrameTotal;

                for (int i = 0; i < nFrames; i++)
                {
                    if (isKeyFrame(aviStream.ToInt32(), i))
                        videoInfo.KeyFrames.Add(i);
                }

                setStatus(videoInfo.KeyFrames.Count + " detectados");

                AVIFileWrapper.AVIStreamRelease(aviStream);
                AVIFileWrapper.AVIFileRelease(aviFile);
                AVIFileWrapper.AVIFileExit();
                KeyframesAvailable = true;
                /*
                nextK.Enabled = true;
                prevK.Enabled = true;

                drawKeyFrameBox();
                 */

            }
            catch
            {
                /*
                nextK.Enabled = false;
                prevK.Enabled = false;
                keyFrameBox.Visible = false;
                 */
                KeyframesAvailable = false;
            }

            if (openFile != null && al.Count > 1 && gridASS.RowCount>0)
            {
                gridASS.Rows[1].Selected = true;
                gridASS.Rows[0].Selected = true;
                gridASS.Rows[1].Selected = false;

            }

            frameTime = new Hashtable();
            for (int i = 0; i < FrameTotal; i++)
                frameTime.Add(i, new Tiempo((double)((double)i / videoInfo.FrameRate)));

            isVideoLoaded = true;

            updateMenuEnables();
            mediaControl.Pause();

            setStatus("Vídeo " + fileName + " cargado. [DirectShow]");

            script.GetHeader().SetHeaderValue("Video File", fileName);

            if (isKeyframeGuessNeeded())
                KeyframeGuess(false);
            //FrameIndex = 0;
        }
Exemplo n.º 33
0
        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;
                    iVW = null;
                    iBV = null;
                }
            }
        }
Exemplo n.º 34
0
        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;
        }
Exemplo n.º 35
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();
            }
        }
Exemplo n.º 36
0
        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;
                    }

                    // 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.videoWindow != null)
                        this.videoWindow = null;
                    if (this.graphBuilder != null)
                    {
                        while (Marshal.ReleaseComObject(this.graphBuilder) > 0) ;
                        this.graphBuilder = null;
                    }
                    //bad way
                    //if (this.graphBuilder != null)
                    //Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null;

                    GC.Collect();
                }
            }
            catch (Exception ex)
            {
                ErrorException("CloseInterfaces: " + ex.Message, ex.StackTrace);
            }
        }
Exemplo n.º 37
0
 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_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;
     }
 }
Exemplo n.º 38
0
        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
              {
              }
        }
Exemplo n.º 39
0
        protected virtual void DoStopInternal(object state)
        {
            try
            {
                //ResetVolumeLevels();
#if HAVE_SAMPLES
                ReleaseAudioSampleGrabber();
#endif

                if (mediaControl != null)
                {
                    mediaControl.Stop();

                    mediaControl = null;
                    mediaPosition = null;
                    videoWindow = null;
                    basicVideo = null;
                    basicAudio = null;
                    mediaEvent = null;
                }

                GC.Collect();
            }
            catch (Exception ex)
            {
                // This is running on other thread than the DSRenderer,
                // so its exceptions are not caught in MediaRenderer
                ErrorDispatcher.DispatchError(ex);
            }
        }
Exemplo n.º 40
0
        public void ResumePlayingVideo()
        {
            Debug.Assert(IsPlaying);

            lock(fgmLock)
            {
                if(fgmState != FilterGraph.State.Running)
                {
                    fgmState = FilterGraph.State.Running;

                    if (fgm != null)
                    {
                        // Due to some interesting bugs(?) in DShow, it is necessary for us to keep
                        // track of our state and re-initialize iBV and iVW
                        iBV = (IBasicVideo)fgm;
                        iVW = (IVideoWindow)fgm;
                        iVW.Owner = videoWindowHandle.ToInt32();
                        iVW.Visible = -1;

                        ResizeVideoStream(videoWindowHeight, videoWindowWidth);

                        // 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.LocalVideoPlayStopped;
                    ((FAudioVideo)form).UpdateVideoUI(uiState);
                }
            }
        }
Exemplo n.º 41
0
        public void StopPlayingVideo()
        {
            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();
                        }

                        // Due to some interesting bugs(?) in DShow, it is necessary for us to keep
                        // track of our state and re-initialize iBV and iVW
                        // We set the Owner to zero, otherwise when a window goes away and a new one
                        // takes its place we can't control it.
                        fgm.Stop();

                        if(iVW != null)
                        {
                            iVW.Visible = 0;
                            iVW.Owner = 0;
                            iVW = null;
                        }

                        iBV = null;
                    }

                    uiState |= (int)FAudioVideo.UIState.LocalVideoPlayStopped;
                    ((FAudioVideo)form).UpdateVideoUI(uiState);
                }
            }
        }
Exemplo n.º 42
0
    private void LoadMovieInWindow(string filename)
    {
      int hr = 0;

      if (filename == string.Empty)
        return;

      this.graphBuilder = (IGraphBuilder)new FilterGraph();
      this.captureGraphBuilder = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();
      this.vmr9 = new VideoMixingRenderer9();
      this.vmrConfig = this.vmr9 as IVMRFilterConfig9;

      // Attach the filter graph to the capture graph
      hr = this.captureGraphBuilder.SetFiltergraph(this.graphBuilder);
      DsError.ThrowExceptionForHR(hr);

      hr = this.graphBuilder.AddFilter(vmr9 as IBaseFilter, "VideoMixingRenderer9");
      DsError.ThrowExceptionForHR(hr);

      hr = this.vmrConfig.SetRenderingMode(VMR9Mode.Windowless);
      DsError.ThrowExceptionForHR(hr);
      this.windowLessControl = this.vmr9 as IVMRWindowlessControl9;
      this.windowLessControl.SetVideoClippingWindow(this.Handle);
      this.windowLessControl.SetVideoPosition(null, new DsRect(0, 0, this.ClientSize.Width, this.ClientSize.Height));

      IBaseFilter fileSourceFilter;
      hr = this.graphBuilder.AddSourceFilter(filename, "WebCamSource", out fileSourceFilter);
      DsError.ThrowExceptionForHR(hr);

      hr = this.captureGraphBuilder.RenderStream(null, null, fileSourceFilter, null, vmr9 as IBaseFilter);
      DsError.ThrowExceptionForHR(hr);

      //// 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)
      {
        this.windowLessControl = this.vmr9 as IVMRWindowlessControl9;
        this.windowLessControl.SetVideoClippingWindow(this.Handle);
        this.windowLessControl.SetVideoPosition(null, new DsRect(0, 0, this.ClientSize.Width, this.ClientSize.Height));

        //hr = InitVideoWindow();
        //DsError.ThrowExceptionForHR(hr);

        GetFrameStepInterface();
      }

      // Complete window initialization
      //this.isFullScreen = false;
      this.currentPlaybackRate = 1.0;
      //UpdateToolTip();

#if DEBUG
      rot = new DsROTEntry(this.graphBuilder);
#endif
    }
Exemplo n.º 43
0
        private void BuildAndRunGraph(string url)
        {
            graphBuilder = (IGraphBuilder) new FilterGraph();

            var sourceBaseFilter = (IBaseFilter) new LAVSplitterSource();

            ILAVSplitterSourceSettings sourceSettings = (ILAVSplitterSourceSettings)sourceBaseFilter;
            var hr = sourceSettings.SetNetworkStreamAnalysisDuration(5000);

            DsError.ThrowExceptionForHR(hr);

            hr = graphBuilder.AddFilter(sourceBaseFilter, "Lav splitter source");
            DsError.ThrowExceptionForHR(hr);

            hr = ((IFileSourceFilter)sourceBaseFilter).Load(url, new AMMediaType());
            DsError.ThrowExceptionForHR(hr);

            IBaseFilter decoderBaseFilter;
            string      decoderOutputPinName;

            if (IsVideoH264(sourceBaseFilter))
            {
                //microsoft decoder
                decoderBaseFilter = FilterGraphTools.AddFilterFromClsid(graphBuilder,
                                                                        new Guid("{212690FB-83E5-4526-8FD7-74478B7939CD}"), "decoder");
                FilterGraphTools.ConnectFilters(graphBuilder, sourceBaseFilter, "Video", decoderBaseFilter, "Video Input",
                                                useIntelligentConnect: true);

                decoderOutputPinName = "Video Output 1";
            }
            else
            {
                //lav
                decoderBaseFilter = FilterGraphTools.AddFilterFromClsid(graphBuilder,
                                                                        new Guid("{EE30215D-164F-4A92-A4EB-9D4C13390F9F}"), "decoder");
                FilterGraphTools.ConnectFilters(graphBuilder, sourceBaseFilter, "Video", decoderBaseFilter, "Input",
                                                useIntelligentConnect: true);
                decoderOutputPinName = "Output";
            }

            IBaseFilter pEVR = (IBaseFilter) new EnhancedVideoRenderer();

            hr = graphBuilder.AddFilter(pEVR, "Enhanced Video Renderer");
            DsError.ThrowExceptionForHR(hr);

            FilterGraphTools.ConnectFilters(graphBuilder, decoderBaseFilter, decoderOutputPinName, pEVR, "EVR Input0",
                                            useIntelligentConnect: true);

            IMFVideoDisplayControl m_pDisplay;

            InitializeEVR(pEVR, 1, out m_pDisplay);

            //render audio from audio splitter
            if (IsAudioPinPresent(sourceBaseFilter))
            {
                var audioDecoderBaseFilter = FilterGraphTools.AddFilterFromClsid(graphBuilder,
                                                                                 new Guid("{E8E73B6B-4CB3-44A4-BE99-4F7BCB96E491}"), "audio decoder");
                FilterGraphTools.ConnectFilters(graphBuilder, sourceBaseFilter, "Audio", audioDecoderBaseFilter, "Input",
                                                useIntelligentConnect: true);
                FilterGraphTools.RenderPin(graphBuilder, audioDecoderBaseFilter, "Output");
            }


            mediaControl = (IMediaControl)graphBuilder;
            mediaEventEx = (IMediaEventEx)graphBuilder;


            basicVideo = graphBuilder as IBasicVideo;
            basicAudio = graphBuilder as IBasicAudio;

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

            isFullScreen = false;

            Focus();

            hr = mediaControl.Run();
            DsError.ThrowExceptionForHR(hr);

            currentState = PlayState.Running;
        }
Exemplo n.º 44
0
        private void MainFormLoader()
        {
            if (!Application.Current.Dispatcher.CheckAccess())
                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new MainFormLoaderDelegate(MainFormLoader));
            else
            {
                try
                {
                    // If we have ANY file open, close it and shut down DirectShow
                    if (this.currentState != PlayState.Init)
                        CloseClip();

                    if (isInfoLoading)
                    {
                        string info = "";
                        double maximum = 0;
                        double titleduration = 0.0;
                        int index_of_maximum = 0;
                        int num = 0;

                        //забиваем длительность
                        foreach (object obj in dvd)
                        {
                            string[] titles = (string[])obj;
                            string ifopath = Calculate.GetIFO(titles[0]);

                            if (File.Exists(ifopath))
                            {
                                //получаем информацию из ифо
                                VStripWrapper vs = new VStripWrapper();
                                vs.Open(ifopath);
                                titleduration = vs.Duration().TotalSeconds;
                                info = vs.GetVideoInfo();
                                vs.Close();

                                string titlenum = Calculate.GetTitleNum(titles[0]);
                                combo_titles.Items.Add("T" + titlenum + " " + info + " " + Calculate.GetTimeline(titleduration) + " - " + titles.Length + " file(s)");
                            }
                            else
                            {
                                //метод если нет IFO (через DS)
                                info = "";
                                bool first = true, error = false;
                                foreach (string tilte in titles)
                                {
                                    try
                                    {
                                        int hr = 0;
                                        this.graphBuilder = (IGraphBuilder)new FilterGraph();

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

                                        //определяем различные параметры
                                        if (first)
                                        {
                                            int resw, resh;
                                            double AvgTimePerFrame;
                                            this.basicVideo = this.graphBuilder as IBasicVideo;
                                            hr = basicVideo.get_SourceWidth(out resw);
                                            DsError.ThrowExceptionForHR(hr);
                                            hr = basicVideo.get_SourceHeight(out resh);
                                            DsError.ThrowExceptionForHR(hr);
                                            hr = basicVideo.get_AvgTimePerFrame(out AvgTimePerFrame);
                                            DsError.ThrowExceptionForHR(hr);
                                            double framerate = 1 / AvgTimePerFrame;
                                            string system = (framerate == 25.0 || framerate == 50.0) ? "PAL" : "NTSC";

                                            info = resw + "x" + resh + " " + system;
                                            first = false;
                                        }

                                        //определяем длительность
                                        double cduration = 0.0;
                                        this.mediaPosition = (IMediaPosition)this.graphBuilder;
                                        hr = mediaPosition.get_Duration(out cduration);
                                        DsError.ThrowExceptionForHR(hr);

                                        titleduration += cduration;
                                    }
                                    catch (Exception)
                                    {
                                        error = true;
                                    }
                                    finally
                                    {
                                        //освобождаем ресурсы
                                        CloseInterfaces();
                                    }
                                }

                                string titlenum = Calculate.GetTitleNum(titles[0]);
                                combo_titles.Items.Add("T" + titlenum + " " + info + " " + Calculate.GetTimeline(titleduration) + (error ? " ERROR" : "") + " - " + titles.Length + " file(s)");
                            }

                            //Ищем самый продолжительный титл
                            if (titleduration > maximum)
                            {
                                maximum = titleduration;
                                index_of_maximum = num;
                            }
                            num += 1;
                        }

                        combo_titles.Items.RemoveAt(0);
                        combo_titles.SelectedIndex = index_of_maximum;
                        this.isInfoLoading = false;
                    }

                    string[] deftitles = (string[])dvd[combo_titles.SelectedIndex];

                    if (combo_vob.Tag == null)
                    {
                        //Загружаем титл, выбираем первый воб
                        combo_vob.Items.Clear();
                        foreach (string vob in deftitles)
                            combo_vob.Items.Add(Path.GetFileName(vob).ToUpper());
                        combo_vob.SelectedIndex = 0;

                        this.filepath = deftitles[0];
                        string title_s = Calculate.GetTitleNum(this.filepath);
                        textbox_name.Text = Calculate.GetDVDName(this.filepath) + " T" + title_s;
                        m.infilepath = this.filepath;
                        m.infileslist = deftitles;
                    }
                    else
                    {
                        //Выбираем конкретный воб (только для показа в этом окне)
                        this.filepath = deftitles[(int)combo_vob.Tag];
                        combo_vob.Tag = null;

                        //При ошибке могло сброситься
                        string title_s = Calculate.GetTitleNum(this.filepath);
                        textbox_name.Text = Calculate.GetDVDName(this.filepath) + " T" + title_s;
                    }

                    //Определяем аспект для плейера (чтоб не вызывать еще раз MediaInfo)
                    string aspect = Calculate.GetRegexValue(@"\s(\d+:\d+)\s", combo_titles.SelectedItem.ToString());
                    if (!string.IsNullOrEmpty(aspect))
                    {
                        if (aspect == "4:3") in_ar = 4.0 / 3.0;
                        else if (aspect == "16:9") in_ar = 16.0 / 9.0;
                        else if (aspect == "2.2:1") in_ar = 2.21;
                    }

                    // Reset status variables
                    this.IsAudioOnly = true;
                    this.currentState = PlayState.Stopped;

                    // Start playing the media file
                    if (Settings.PlayerEngine != Settings.PlayerEngines.MediaBridge)
                        PlayMovieInWindow(this.filepath);
                    else
                        PlayWithMediaBridge(this.filepath);

                    this.Focus();
                }
                catch (Exception ex)
                {
                    CloseClip();
                    this.filepath = String.Empty;
                    textbox_name.Text = Languages.Translate("Error") + "...";
                    ErrorException(((isInfoLoading) ? "SortingTitles: " : "PlaySelectedVOB: ") + ex.Message, ex.StackTrace);
                }
            }
        }
Exemplo n.º 45
0
        private void closeVidDShow()
        {
            if (mediaControl != null)
                mediaControl.Stop();

            if (videoWindow != null)
            {
                videoWindow.put_Visible(DirectShowLib.OABool.False);
                videoWindow.put_Owner(IntPtr.Zero);
            }
            actualizaFrames.Enabled = false;
            PlayInRange.Enabled = false;

            //graphBuilder.Abort();
            mediaControl = null;
            //mediaEventEx = null;
            videoWindow = null;
            //basicAudio = null;
            basicVideo = null;
            mediaSeeking = null;
            mediaPosition = null;
            //frameStep = null;

            Marshal.ReleaseComObject(graphBuilder);
            graphBuilder = null;
            GC.Collect();
            isVideoLoaded = true;
            updateMenuEnables();
        }
Exemplo n.º 46
0
        private void closeAll()
        {
            timer1.Enabled = false;
            timer2.Enabled = false;
            AutoSaveTimer.Enabled = false;
            estadoConexion.Enabled = false;
            videoPanel.Visible = false;

            if (videoWindow != null)
            {
                videoWindow.put_Visible(DirectShowLib.OABool.False);
                videoWindow.put_Owner(IntPtr.Zero);
            }
            videoPanel.Dispose();
            if (mediaControl!=null) mediaControl.Stop();
            // if (graphBuilder!=null) graphBuilder.Abort();

            mediaControl = null;
            //mediaEventEx = null;
            videoWindow = null;
            basicAudio = null;
            basicVideo = null;
            mediaSeeking = null;
            mediaPosition = null;

            try
            {

                Marshal.ReleaseComObject(graphBuilder);
                graphBuilder = null;
            }
            catch { }

            GC.Collect();

            //frameStep = null;
        }
Exemplo n.º 47
0
        //
        // 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;
            }
        }
Exemplo n.º 48
0
        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 DEBUG
                    try
                    {
                        if (rot != null)
                        {
                            rot.Dispose();
                            rot = null;
                        }
                    }
                    catch { }
                    //#endif

                    if (dvdSubtitle != null)
                        Marshal.ReleaseComObject(dvdSubtitle);
                    dvdSubtitle = null;

                    if (dvdCtrl != null)
                    {
                        hr = dvdCtrl.SetOption(DvdOptionFlag.ResetOnStop, true);
                    }

                    if (cmdOption != null)
                    {
                        Marshal.ReleaseComObject(cmdOption);
                        cmdOption = null;
                    }

                    pendingCmd = false;

                    dvdCtrl = null;
                    if (dvdInfo != null)
                    {
                        Marshal.ReleaseComObject(dvdInfo);
                        dvdInfo = null;
                    }

                    if (this.mediaEventEx != null)
                    {
                        if (dvdGraph != null)
                            hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, WM.DVD_EVENT, IntPtr.Zero);
                        else
                            hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, WM.NULL, IntPtr.Zero);
                        //DsError.ThrowExceptionForHR(hr);
                    }

                    if (evrDisplay != null)
                    {
                        //evrDisplay.SetVideoWindow(IntPtr.Zero);
                        Marshal.ReleaseComObject(evrDisplay);
                    }
                    evrDisplay = null;
                    if (this.evrRenderer != null)
                        Marshal.ReleaseComObject(evrRenderer);
                    evrRenderer = null;

                    // 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;
                    if (this.dvdGraph != null)
                        Marshal.ReleaseComObject(dvdGraph); dvdGraph = null;

                    GC.Collect();
                }
            }
            catch
            {
            }
        }
Exemplo n.º 49
0
        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);
            }
        }
Exemplo n.º 50
0
        private void Form1_Load(object sender, EventArgs e)
        {
            m_PictureReady = new ManualResetEvent(false);

            //  ¨PlayMovieInWindow( "c:\\temp\\beckscen2.avi" );
            int hr;

            this.graphBuilder = (IGraphBuilder)new FilterGraph();
            //            this.graphBuilder.AddFilter(

            // Get the SampleGrabber interface
            ISampleGrabber sampGrabber = new SampleGrabber() as ISampleGrabber;

            IBaseFilter ibfRenderer = null;
            IBaseFilter capFilter = null;
            IPin iPinInFilter = null;
            IPin iPinOutFilter = null;
            IPin iPinInDest = null;

            // Add the video source
            hr = graphBuilder.AddSourceFilter(Filename, "Ds.NET FileFilter", out capFilter);
            DsError.ThrowExceptionForHR(hr);

            // Hopefully this will be the video pin
            IPin iPinOutSource = DsFindPin.ByDirection(capFilter, PinDirection.Output, 0);

            IBaseFilter baseGrabFlt = sampGrabber as IBaseFilter;
            ConfigureSampleGrabber(sampGrabber);

            iPinInFilter = DsFindPin.ByDirection(baseGrabFlt, PinDirection.Input, 0);
            iPinOutFilter = DsFindPin.ByDirection(baseGrabFlt, PinDirection.Output, 0);

            // Add the frame grabber to the graph
            hr = graphBuilder.AddFilter(baseGrabFlt, "Ds.NET Grabber");
            DsError.ThrowExceptionForHR(hr);

            hr = graphBuilder.Connect(iPinOutSource, iPinInFilter);
            DsError.ThrowExceptionForHR(hr);

            // Get the default video renderer
            ibfRenderer = (IBaseFilter)new VideoRendererDefault();

            // Add it to the graph
            hr = graphBuilder.AddFilter(ibfRenderer, "Ds.NET VideoRendererDefault");
            DsError.ThrowExceptionForHR(hr);
            iPinInDest = DsFindPin.ByDirection(ibfRenderer, PinDirection.Input, 0);

            // Connect the graph.  Many other filters automatically get added here
            hr = graphBuilder.Connect(iPinOutFilter, iPinInDest);
            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;

            hr = this.videoWindow.put_Owner(panel1.Handle);
            DsError.ThrowExceptionForHR(hr);

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

            if (this.basicVideo == null)
                return;

            int lHeight, lWidth;
            hr = this.basicVideo.GetVideoSize(out lWidth, out lHeight);

            Console.WriteLine("video: %d x %d\n", lWidth, lHeight);

            m_videoWidth = lWidth;
            m_videoHeight = lHeight;
            SaveSizeInfo(sampGrabber);
            newbitmap = new Bitmap(lWidth, lHeight, PixelFormat.Format24bppRgb);
            origbitmap = new Bitmap(lWidth, lHeight, PixelFormat.Format24bppRgb);
            m_ImageChanged = true;
            pictureBox1.Width = lWidth;
            pictureBox1.Height = lHeight;
            pictureBox2.Width = lWidth;
            pictureBox2.Height = lHeight;
            pictureBox2.Top = pictureBox1.Top + lHeight + 4;

            duration = 0.0f;
            this.mediaPosition.get_Duration(out duration);

            m_ipBuffer = Marshal.AllocCoTaskMem(Math.Abs(m_stride) * m_videoHeight);

            //             this.ClientSize = new Size(lWidth, lHeight);
            Application.DoEvents();

            hr = this.videoWindow.SetWindowPosition(0, 0, panel1.Width, panel1.Height);

            this.mediaControl.Run();
            timer1.Enabled = true;

            //            buildCaptureGRaph( this.de ( (capDevices[iDeviceNum], iWidth, iHeight, iBPP, hControl);

            //            buildCaptureaph();
        }
Exemplo n.º 51
0
        private void LoadMovieInWindow(string filename)
        {
            int hr = 0;

            if (filename == string.Empty)
            {
                return;
            }

            this.graphBuilder        = (IGraphBuilder) new FilterGraph();
            this.captureGraphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();
            this.vmr9      = new VideoMixingRenderer9();
            this.vmrConfig = this.vmr9 as IVMRFilterConfig9;

            // Attach the filter graph to the capture graph
            hr = this.captureGraphBuilder.SetFiltergraph(this.graphBuilder);
            DsError.ThrowExceptionForHR(hr);

            hr = this.graphBuilder.AddFilter(vmr9 as IBaseFilter, "VideoMixingRenderer9");
            DsError.ThrowExceptionForHR(hr);

            hr = this.vmrConfig.SetRenderingMode(VMR9Mode.Windowless);
            DsError.ThrowExceptionForHR(hr);
            this.windowLessControl = this.vmr9 as IVMRWindowlessControl9;
            this.windowLessControl.SetVideoClippingWindow(this.Handle);
            this.windowLessControl.SetVideoPosition(null, new DsRect(0, 0, this.ClientSize.Width, this.ClientSize.Height));

            IBaseFilter fileSourceFilter;

            hr = this.graphBuilder.AddSourceFilter(filename, "WebCamSource", out fileSourceFilter);
            DsError.ThrowExceptionForHR(hr);

            hr = this.captureGraphBuilder.RenderStream(null, null, fileSourceFilter, null, vmr9 as IBaseFilter);
            DsError.ThrowExceptionForHR(hr);

            //// 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)
            {
                this.windowLessControl = this.vmr9 as IVMRWindowlessControl9;
                this.windowLessControl.SetVideoClippingWindow(this.Handle);
                this.windowLessControl.SetVideoPosition(null, new DsRect(0, 0, this.ClientSize.Width, this.ClientSize.Height));

                //hr = InitVideoWindow();
                //DsError.ThrowExceptionForHR(hr);

                GetFrameStepInterface();
            }

            // Complete window initialization
            //this.isFullScreen = false;
            this.currentPlaybackRate = 1.0;
            //UpdateToolTip();

#if DEBUG
            rot = new DsROTEntry(this.graphBuilder);
#endif
        }
Exemplo n.º 52
0
        private void MainFormLoader()
        {
            if (!Application.Current.Dispatcher.CheckAccess())
                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new MainFormLoaderDelegate(MainFormLoader));
            else
            {
                try
                {
                    // If we have ANY file open, close it and shut down DirectShow
                    if (this.currentState != PlayState.Init)
                        CloseClip();

                    //список плохих титлов
                    ArrayList badlist = new ArrayList();

                    if (isInfoLoading)
                    {
                        double maximum = 0;
                        int index_of_maximum = 0;
                        int num = 0;

                        //забиваем длительность
                        foreach (object obj in dvd)
                        {
                            string[] titles = (string[])obj;
                            string ifopath = Calculate.GetIFO(titles[0]);

                            if (File.Exists(ifopath))
                            {
                                MediaInfoWrapper media = new MediaInfoWrapper();
                                media.Open(ifopath);
                                string info = media.Width + "x" + media.Height + " " + media.AspectString + " " + media.Standart;
                                media.Close();

                                //получаем информацию из ифо
                                VStripWrapper vs = new VStripWrapper();
                                vs.Open(ifopath);
                                double titleduration = vs.Duration().TotalSeconds;
                                //string   info = vs.Width() + "x" + vs.Height() + " " + vs.System(); //При обращении к ifoGetVideoDesc на некоторых системах происходит вылет VStrip.dll..
                                //Теперь нужная инфа будет браться из МедиаИнфо..
                                vs.Close();

                                string titlenum = Calculate.GetTitleNum(titles[0]);
                                combo_titles.Items.Add("T" + titlenum + " " + info + " " + Calculate.GetTimeline(titleduration) + " - " + titles.Length + " file(s)");

                                //Ищем самый продолжительный титл
                                if (titleduration > maximum)
                                {
                                    maximum = titleduration;
                                    index_of_maximum = num;
                                }
                                num += 1;
                            }
                            //метод если нет IFO
                            else
                            {
                                try
                                {
                                    int n = 0;
                                    double titleduration = 0.0;
                                    string info = "";
                                    foreach (string tilte in titles)
                                    {
                                        int hr = 0;

                                        this.graphBuilder = (IGraphBuilder)new FilterGraph();

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

                                        // QueryInterface for DirectShow interfaces
                                        this.mediaControl = (IMediaControl)this.graphBuilder;
                                        this.mediaPosition = (IMediaPosition)this.graphBuilder;

                                        //определяем длительность
                                        double cduration = 0.0;
                                        hr = mediaPosition.get_Duration(out cduration);
                                        DsError.ThrowExceptionForHR(hr);

                                        //определяем различные параметры
                                        if (n == 0)
                                        {
                                            this.basicVideo = this.graphBuilder as IBasicVideo;
                                            //this.basicAudio = this.graphBuilder as IBasicAudio;
                                            int resw;
                                            int resh;
                                            double AvgTimePerFrame;
                                            hr = basicVideo.get_SourceWidth(out resw);
                                            DsError.ThrowExceptionForHR(hr);
                                            hr = basicVideo.get_SourceHeight(out resh);
                                            DsError.ThrowExceptionForHR(hr);
                                            hr = basicVideo.get_AvgTimePerFrame(out AvgTimePerFrame);
                                            double framerate = 1 / AvgTimePerFrame;
                                            string system = "NTSC";
                                            if (framerate == 25.0)
                                                system = "PAL";

                                            info += resw + "x" + resh + " " + system + " ";
                                        }

                                        //освобождаем ресурсы
                                        CloseInterfaces();

                                        titleduration += cduration;

                                        n++;
                                    }

                                    string titlenum = Calculate.GetTitleNum(titles[0]);
                                    combo_titles.Items.Add("T" + titlenum + " " + info + Calculate.GetTimeline(titleduration));
                                }
                                catch
                                {
                                    badlist.Add(obj);
                                    CloseInterfaces();
                                }
                            }
                        }

                        combo_titles.Items.RemoveAt(0);
                        combo_titles.SelectedIndex = index_of_maximum;
                        this.isInfoLoading = false;
                    }

                    //удаляем плохие титлы
                    foreach (object obj in badlist)
                        dvd.Remove(obj);

                    //загружаем титл
                    string[] deftitles = (string[])dvd[combo_titles.SelectedIndex];
                    this.filepath = deftitles[0];
                    string title_s = Calculate.GetTitleNum(this.filepath);
                    textbox_name.Text = Calculate.GetDVDName(this.filepath) + " T" + title_s;
                    m.infilepath = this.filepath;
                    m.infileslist = deftitles;

                    //Определяем аспект для DirectShow плейера (чтоб не вызывать еще раз MediaInfo)
                    string aspect = Calculate.GetRegexValue(@"\s\d+x\d+\s(\d+:\d+)\s", combo_titles.SelectedItem.ToString());
                    if (!string.IsNullOrEmpty(aspect))
                    {
                        if (aspect == "4:3") in_ar = 4.0 / 3.0;
                        else if (aspect == "16:9") in_ar = 16.0 / 9.0;
                        else if (aspect == "2.2:1") in_ar = 2.21;
                    }

                    // Reset status variables
                    this.currentState = PlayState.Stopped;

                    // Start playing the media file
                    if (Settings.PlayerEngine != Settings.PlayerEngines.MediaBridge)
                        PlayMovieInWindow(this.filepath);
                    else
                        PlayWithMediaBridge(this.filepath);
                }
                catch (Exception ex)
                {
                    textbox_name.Text = "";
                    CloseClip();
                    this.filepath = String.Empty;
                    ErrorException("MainFormLoader: " + ex.Message, ex.StackTrace);
                }
            }
        }
Exemplo n.º 53
0
        /// <summary>
        /// Sets the video geometry based on the IBasicVideo interface
        /// </summary>
        private void SetVideoDimensions(IBasicVideo basicVideo)
        {
            if (basicVideo == null)
            {
                NaturalVideoHeight = 0;
                NaturalVideoWidth = 0;
                HasVideo = false;

                /* Since we have no video
                 * we can release the custom
                 * allocator */
                FreeCustomAllocator();

                return;
            }

            HasVideo = true;
        }
Exemplo n.º 54
0
        private void CloseInterfaces()
        {
            //int hr = 0;

            try
            {
                lock (this)
                {
                    //// 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);
                    //}

                    //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 (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
            }
        }
Exemplo n.º 55
0
        private void translateW_Load(object sender, EventArgs e)
        {
            //this.MaximumSize = this.Size;
            //this.MinimumSize = this.Size;
            toolStripStatusLabel2.Text = "Cargando el Asistente de Traducción...";
            // cargamos script
            autoComplete = new ArrayList();
            al = mW.al;
            gridCont.RowCount = al.Count;

            bool hasAutoComplete = (mW.script.GetHeader().GetHeaderValue("AutoComplete") != string.Empty);

            for (int i = 0; i < al.Count; i++)
            {
                lineaASS lass = (lineaASS)al[i];
                gridCont[0, i].Value = lass.personaje;
                if (!autoComplete.Contains(lass.personaje) && !hasAutoComplete)
                    if (lass.personaje.Trim()!="")
                        autoComplete.Add(lass.personaje);
                gridCont[1, i].Value = lass.texto;
            }
            if (hasAutoComplete) InsertAutoCompleteFromScript();

            labelLineaActual.Text = "1 de " + (al.Count) + " (0%)";
            textPersonaje.Text = gridCont[0, 0].Value.ToString();
            textOrig.Text = gridCont[1, 0].Value.ToString();

            // cargamos video

            graphBuilder = (IGraphBuilder)new FilterGraph();
            graphBuilder.RenderFile(videoInfo.FileName, null);
            mediaControl = (IMediaControl)graphBuilder;
            // mediaEventEx = (IMediaEventEx)this.graphBuilder;
            mediaSeeking = (IMediaSeeking)graphBuilder;
            mediaPosition = (IMediaPosition)graphBuilder;
            basicVideo = graphBuilder as IBasicVideo;
            basicAudio = graphBuilder as IBasicAudio;
            videoWindow = graphBuilder as IVideoWindow;

            try
            {
                int x, y; double atpf;
                basicVideo.GetVideoSize(out x, out y);
                basicVideo.get_AvgTimePerFrame(out atpf);
                videoInfo.FrameRate = Math.Round(1 / atpf, 3);

                int new_x = videoPanel.Width;
                int new_y = (new_x * y) / x;
                videoWindow.put_Height(new_x);
                videoWindow.put_Width(new_y);
                videoWindow.put_Owner(videoPanel.Handle);
                videoPanel.Size = new System.Drawing.Size(new_x, new_y);
                videoWindow.SetWindowPosition(0, 0, videoPanel.Width, videoPanel.Height);
                videoWindow.put_WindowStyle(WindowStyle.Child);
                videoWindow.put_Visible(DirectShowLib.OABool.True);
                mediaSeeking.SetTimeFormat(DirectShowLib.TimeFormat.Frame);

                mediaControl.Run();
            }
            catch { mW.errorMsg("Imposible cargar el vídeo. Debe haber algún problema con el mismo, y el asistente será muy inestable"); }
            // activamos timers & handlers

            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Enabled = true;
            timer2.Tick += new EventHandler(timer2_Tick);
            AutoSaveTimer.Tick += new EventHandler(timer3_Tick);
            AutoSaveTimer.Enabled = true;

            gridCont.CellClick += new DataGridViewCellEventHandler(gridCont_CellClick);
            textPersonaje.TextChanged += new EventHandler(textPersonaje_TextChanged);
            textTradu.TextChanged += new EventHandler(textTradu_TextChanged);
            textTradu.KeyUp += new KeyEventHandler(textBox1_KeyUp);
            textTradu.KeyDown += new KeyEventHandler(textTradu_KeyDown);
            textTradu.KeyPress += new KeyPressEventHandler(textTradu_KeyPress);
            textPersonaje.KeyDown += new KeyEventHandler(textPersonaje_KeyDown);
            textPersonaje.KeyPress += new KeyPressEventHandler(textPersonaje_KeyPress);
            button8.GotFocus += new EventHandler(button8_GotFocus);
            button9.GotFocus += new EventHandler(button9_GotFocus);
            gridCont.DoubleClick += new EventHandler(gridCont_DoubleClick);
            gridCont.SelectionChanged += new EventHandler(gridCont_SelectionChanged);
            gridCont.KeyUp += new KeyEventHandler(gridCont_KeyUp);
            listBox1.KeyUp += new KeyEventHandler(listBox1_KeyUp);
            textToAdd.KeyPress += new KeyPressEventHandler(textToAdd_KeyPress);
            progressBar1.MouseDown += new MouseEventHandler(progressBar1_MouseDown);
            tiempoInicio_.TimeValidated += new TimeTextBox.OnTimeTextBoxValidated(tiempo_TimeValidated);
            tiempoFin_.TimeValidated += new TimeTextBox.OnTimeTextBoxValidated(tiempo_TimeValidated);
            this.Move += new EventHandler(translateW_Move);

            //textTradu.ContextMenu = new ASSTextBoxRegExDefaultContextMenu(textTradu);

            mediaControl.Pause();

            // cargar de config

            try
            {
                checkAutoComplete.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_autoC"));
                checkTagSSA.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_tagSSA"));
                checkComment.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_Comment"));
                checkVideo.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_aud"));
                checkAudio.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_vid"));
                checkSaveTime.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_preTime"));
            }
            catch {}

            try
            {
                AutoSaveTimer.Interval = int.Parse(mW.getFromConfigFile("translateW_AutoSaveInterval"));
            }
            catch
            {
                AutoSaveTimer.Interval = 30000;
            }

            // fin de inicializacion vil
            textTradu.Focus();

            try
            {
                string[] bleh = mW.getFromConfigFileA("translateW_Reference");
                for (int i = 0; i < bleh.Length; i++)
                    Diccionarios.Add(bleh[i]);
            }
            catch
            {
                Diccionarios.Add("WordReference|http://www.wordreference.com/");
                Diccionarios.Add("Wikipedia|http://es.wikipedia.org");
                Diccionarios.Add("RAE|http://www.rae.es");
                Diccionarios.Add("Dictionary|http://dictionary.reference.com/");
            }
            diccionarios.DataSource = Diccionarios;

            CreateReferenceTabs();
            UpdateStatusFile();

            TiempoInicio = DateTime.Now;

            Estadisticas.Interval = 1000;
            Estadisticas.Tick += new EventHandler(Estadisticas_Tick);
            Estadisticas.Enabled = true;

            InitRPC();

            archivosView.KeyDown += new KeyEventHandler(archivosView_KeyDown);
            archivosView.SelectedIndexChanged += new EventHandler(archivosView_SelectedIndexChanged);

            textTradu.EnableSpellChecking = mW.spellEnabled;

            if (mW.spellEnabled)
            {
                textTradu.DictionaryPath = mW.dictDir;
                textTradu.Dictionary = mW.ActiveDict;
            }

            toolStripStatusLabel2.Text = "Asistente cargado correctamente.";

            bool showpopup = true;

            try
            {
                showpopup = Convert.ToBoolean(mW.getFromConfigFile("translateW_ShowPopup"));

            }
            catch
            {
                mW.updateReplaceConfigFile("translateW_ShowPopup", showpopup.ToString());
            }

            if (showpopup)
            {
                TranslationStyle estilo = TranslationStyle.FromScriptWithActors;
                translateW_Popup pop = new translateW_Popup(mW);
                switch (pop.ShowDialog())
                {
                    case DialogResult.Yes:
                        estilo = TranslationStyle.FromScriptWithActors;
                        break;
                    case DialogResult.No:
                        estilo = TranslationStyle.FromScriptWithoutActors;
                        break;
                    case DialogResult.Cancel:
                        estilo = TranslationStyle.FromScratch;
                        break;
                    case DialogResult.Ignore:
                        estilo = TranslationStyle.FromScratchAudio;
                        break;
                }

                switch (estilo)
                {
                    case TranslationStyle.FromScriptWithActors:
                        modeSelector.Checked = true;
                        splitText.Checked = false;
                        audioMode.Checked = false;
                        break;
                    case TranslationStyle.FromScriptWithoutActors:
                        modeSelector.Checked = true;
                        splitText.Checked = true;
                        audioMode.Checked = false;
                        break;
                    case TranslationStyle.FromScratch:
                        modeSelector.Checked = false;
                        splitText.Checked = false;
                        audioMode.Checked = false;
                        break;
                    case TranslationStyle.FromScratchAudio:
                        modeSelector.Checked = false;
                        splitText.Checked = true;
                        audioMode.Checked = true;
                        break;
                }
            }
        }
Exemplo n.º 56
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();
        }
Exemplo n.º 57
0
        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;
        }
Exemplo n.º 58
0
 protected virtual HRESULT PreparePlayback()
 {
     m_MediaControl = (IMediaControl)m_GraphBuilder;
     m_BasicVideo = (IBasicVideo)m_GraphBuilder;
     m_MediaSeeking = (IMediaSeeking)m_GraphBuilder;
     m_VideoWindow = (IVideoWindow)m_GraphBuilder;
     m_MediaEventEx = (IMediaEventEx)m_GraphBuilder;
     m_FrameStep = (IVideoFrameStep)m_GraphBuilder;
     SettingUpVideoWindow();
     int hr = m_MediaEventEx.SetNotifyWindow(m_EventControl.Handle, WM_GRAPHNOTIFY, Marshal.GetIUnknownForObject(this));
     Debug.Assert(hr == 0);
     SetVolume(m_bMute ? -10000 : m_iVolume);
     if (m_dRate != 1.0)
     {
         m_MediaSeeking.SetRate(m_dRate);
         m_MediaSeeking.GetRate(out m_dRate);
     }
     if (OnPlaybackReady != null) OnPlaybackReady(this, EventArgs.Empty);
     return (HRESULT)hr;
 }