Esempio n. 1
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;
        }
Esempio n. 2
0
        //
        //Method to start to play a media file
        //
        private void LoadFile(string fName)
        {
            try
            {
                //get the graph filter ready to render
                graphBuilder.RenderFile(fName, null);

                //set the trackbar
                OABool bCsf, bCsb;
                mediaPos.CanSeekBackward(out bCsb);
                mediaPos.CanSeekForward(out bCsf);
                isSeeking = (bCsb == OABool.True) && (bCsf == OABool.True);
                if (isSeeking)
                {
                    trackBar1.Enabled = true;
                }
                else
                {
                    trackBar1.Enabled = false;
                }
                trackBar1.Minimum = 0;

                double duration;
                mediaPos.get_Duration(out duration);
                trackBar1.Maximum = (int)(duration * 100.0);
                Text = fName;

                //check for the ability to step
                frameStep = graphBuilder as IVideoFrameStep;
                if (frameStep.CanStep(1, null) == 0)
                {
                    canStep = true;
                    buttonFramestep.Enabled = true;
                }

                //prepare and set the video window
                videoWin = graphBuilder as IVideoWindow;
                videoWin.put_Owner((IntPtr)panel1.Handle);
                videoWin.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren);
                Rectangle rc = panel1.ClientRectangle;
                videoWin.SetWindowPosition(0, 0, rc.Right, rc.Bottom);
                mediaEvt.SetNotifyWindow((IntPtr)this.Handle, WM_GRAPHNOTIFY, (IntPtr)0);

                //set the different values for controls
                trackBar1.Value           = 0;
                minutes                   = (int)duration / 60;
                seconds                   = (int)duration % 60;
                statusBar1.Panels[0].Text = "Duration: " + minutes.ToString("D2")
                                            + ":m" + seconds.ToString("D2") + ":s";
                graphState = State.Playing;

                this.buttonPlay.Text = "Pause";
                //start the playback
                mediaCtrl.Run();
            }
            catch (Exception) { Text = "Error loading file"; }
        }
        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);
        }
Esempio n. 4
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";
                }
            }
        }
        void TestDuration()
        {
            int    hr;
            double len;

            hr = m_mediaPosition.get_Duration(out len);
            DsError.ThrowExceptionForHR(hr);

            Debug.Assert(len > 4.31, "Get_Duration");
        }
        protected override double GetMediaLength()
        {
            double val = 0;

            if (mediaPosition != null)
            {
                int hr = mediaPosition.get_Duration(out val);
                if (hr >= 0)
                {
                    return(val + double.Epsilon);
                }
            }

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

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

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

                //check capabilities for the IMediaPosition interface
                _pos_canSeek          = (_mediaPosition.put_CurrentPosition(0) == 0);
                _pos_canGetDuration   = (_mediaPosition.get_Duration(out dblTest) == 0);
                _pos_canGetCurrentPos = (_mediaPosition.get_CurrentPosition(out dblTest) == 0);
            }
            catch (Exception)
            {
                _seek_canSeek = false;
                _pos_canSeek  = false;
            }
        }
Esempio n. 8
0
        public override bool Play(string strFile)
        {
            updateTimer = DateTime.Now;
            m_speedRate = 10000;
            GUIGraphicsContext.IsWindowVisible = false;
            m_iVolume        = 100;
            _state           = PlayState.Init;
            m_strCurrentFile = strFile;
            m_bFullScreen    = true;
            m_ar             = GUIGraphicsContext.ARType;

            VideoRendererStatistics.VideoState = VideoRendererStatistics.State.VideoPresent;
            _updateNeeded = true;
            Log.Info("RTSPPlayer:play {0}", strFile);
            //lock ( typeof(VideoPlayerVMR7) )
            {
                CloseInterfaces();
                m_bStarted = false;
                if (!GetInterfaces())
                {
                    m_strCurrentFile = "";
                    CloseInterfaces();
                    return(false);
                }
                int hr = mediaEvt.SetNotifyWindow(GUIGraphicsContext.ActiveForm, WM_GRAPHNOTIFY, IntPtr.Zero);
                if (hr < 0)
                {
                    Error.SetError("Unable to play movie", "Can not set notifications");
                    m_strCurrentFile = "";
                    CloseInterfaces();
                    return(false);
                }

                DirectShowUtil.SetARMode(graphBuilder, AspectRatioMode.Stretched);
                _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder);

                // DsUtils.DumpFilters(graphBuilder);
                hr = _mediaCtrl.Run();
                if (hr < 0)
                {
                    Error.SetError("Unable to play movie", "Unable to start movie");
                    m_strCurrentFile = "";
                    CloseInterfaces();
                    return(false);
                }
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED, 0, 0, 0, 0, 0, null);
                msg.Label = strFile;
                GUIWindowManager.SendThreadMessage(msg);
                _state = PlayState.Playing;
                //Brutus GUIGraphicsContext.IsFullScreenVideo=true;
                m_iPositionX  = GUIGraphicsContext.VideoWindow.X;
                m_iPositionY  = GUIGraphicsContext.VideoWindow.Y;
                m_iWidth      = GUIGraphicsContext.VideoWindow.Width;
                m_iHeight     = GUIGraphicsContext.VideoWindow.Height;
                m_ar          = GUIGraphicsContext.ARType;
                _updateNeeded = true;
                SetVideoWindow();
                mediaPos.get_Duration(out _duration);
                Log.Info("RTSPPlayer:Duration:{0}", _duration);
                if (_mediaType == g_Player.MediaType.TV)
                {
                    //if (_duration < 1) _duration = 1;
                    //SeekAbsolute(_duration - 1);
                }
                else
                {
                    //SeekAbsolute(0);
                }

                OnInitialized();
            }

            // Wait for a while to wait VMR9 to get ready.
            // Implemented due to problems starting to play before VMR9 was ready resulting in black screen.
            Thread.Sleep(200);


            return(true);
        }
Esempio n. 9
0
        public override void Init()
        {
            if (!isPlaying)
            {
                string Filename = "";
                float size = 0;
                double Max = 0;
                int volume = 0;

                graph = new FilterGraph() as IFilterGraph;
                media = graph as IMediaControl;
                eventEx = media as IMediaEventEx;
                igb = media as IGraphBuilder;
                imp = igb as IMediaPosition;
                master.form.Invoke((MethodInvoker)delegate()
                {
                    Filename = master.form.M_Filename.Text;
                    media.RenderFile(Filename);
                    size = (float)master.form.M_PrevSize.Value;
                    master.form.M_PrevSize.Enabled = false;
                    imp.get_Duration(out Max);
                    master.form.M_Seek.Maximum = (int)(Max);
                    master.form.M_Seek.Value = 0;
                    volume = master.form.M_Volume.Value;
                    span = (uint)(1000000.0f / master.form.M_CollectFPS);
                });
                graph.FindFilterByName("Video Renderer", out render);
                if (render != null)
                {
                    window = render as IVideoWindow;
                    window.put_WindowStyle(
                        WindowStyle.Caption | WindowStyle.Child
                        );
                    window.put_WindowStyleEx(
                        WindowStyleEx.ToolWindow
                        );
                    window.put_Caption("ElectronicBoard - VideoPrev -");

                    int Width, Height, Left, Top;
                    window.get_Width(out Width);
                    window.get_Height(out Height);
                    window.get_Left(out Left);
                    window.get_Top(out Top);
                    renderSize.Width = (int)(Width * size);
                    renderSize.Height = (int)(Height * size);
                    Aspect = (float)renderSize.Height / (float)renderSize.Width;
                    window.SetWindowPosition(Left, Top, renderSize.Width, renderSize.Height);

                    eventEx = media as IMediaEventEx;
                    eventEx.SetNotifyWindow(master.form.Handle, WM_DirectShow, IntPtr.Zero);
                    media.Run();
                    foreach (Process p in Process.GetProcesses())
                    {
                        if (p.MainWindowTitle == "ElectronicBoard - VideoPrev -")
                        {
                            renderwindow = p.MainWindowHandle;
                            break;
                        }
                    }
                    isPlaying = true;
                    iba = media as IBasicAudio;
                    iba.put_Volume(volume);

                    //master.form.checkBox3_CheckedChanged(null, null);
                    master.Start();
                }
            }
        }
Esempio n. 10
0
        private void StartCapture()
        {
            int hr;

            ISampleGrabber        sampGrabber = null;
            IBaseFilter           capFilter   = null;
            ICaptureGraphBuilder2 capGraph    = null;

            if (System.IO.File.Exists(txtAviFileName.Text))
            {
                // Get the graphbuilder object
                m_FilterGraph = (IFilterGraph2) new FilterGraph();
                m_mediaCtrl   = m_FilterGraph as IMediaControl;

                // Get the ICaptureGraphBuilder2
                capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();

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

                // Start building the graph
                hr = capGraph.SetFiltergraph(m_FilterGraph);
                DsError.ThrowExceptionForHR(hr);

                // Add the video source
                hr = m_FilterGraph.AddSourceFilter(txtAviFileName.Text, "File Source (Async.)", out capFilter);
                DsError.ThrowExceptionForHR(hr);

                //add AVI Decompressor
                IBaseFilter pAVIDecompressor = (IBaseFilter) new AVIDec();
                hr = m_FilterGraph.AddFilter(pAVIDecompressor, "AVI Decompressor");
                DsError.ThrowExceptionForHR(hr);


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

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


                IBaseFilter vidrender = (IBaseFilter) new VideoRenderer();
                hr = m_FilterGraph.AddFilter(vidrender, "Render");
                DsError.ThrowExceptionForHR(hr);

                IPin captpin = DsFindPin.ByDirection(capFilter, PinDirection.Output, 0);

                IPin samppin = DsFindPin.ByName(baseGrabFlt, "Input");

                hr = m_FilterGraph.Connect(captpin, samppin);
                DsError.ThrowExceptionForHR(hr);

                FileWriter      filewritter = new FileWriter();
                IFileSinkFilter filemux     = (IFileSinkFilter)filewritter;
                //filemux.SetFileName("test.avi",);

                //hr = capGraph.RenderStream(null, MediaType.Video, capFilter, null, vidrender);
                // DsError.ThrowExceptionForHR(hr);

                SaveSizeInfo(sampGrabber);

                // setup buffer
                if (m_handle == IntPtr.Zero)
                {
                    m_handle = Marshal.AllocCoTaskMem(m_stride * m_videoHeight);
                }

                // tell the callback to ignore new images
                m_PictureReady = new ManualResetEvent(false);
                m_bGotOne      = false;
                m_bRunning     = false;

                timer1 = new Thread(timer);
                timer1.IsBackground = true;
                timer1.Start();

                m_mediaextseek = m_FilterGraph as IAMExtendedSeeking;
                m_mediapos     = m_FilterGraph as IMediaPosition;
                m_mediaseek    = m_FilterGraph as IMediaSeeking;
                double length = 0;
                m_mediapos.get_Duration(out length);
                trackBar_mediapos.Minimum = 0;
                trackBar_mediapos.Maximum = (int)length;

                Start();
            }
            else
            {
                MessageBox.Show("File does not exist");
            }
        }
Esempio n. 11
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);
                }
            }
        }
Esempio n. 12
0
        private void PlayMovieInWindow(string filename)
        {
            if (filename == string.Empty) return;

            int hr = 0;
            this.graphBuilder = (IGraphBuilder)new FilterGraph();

            //Добавляем в граф нужный рендерер (Auto - graphBuilder сам выберет рендерер)
            Settings.VRenderers renderer = Settings.VideoRenderer;
            if (renderer == Settings.VRenderers.Overlay)
            {
                IBaseFilter add_vr = (IBaseFilter)new VideoRenderer();
                hr = graphBuilder.AddFilter(add_vr, "Video Renderer");
                DsError.ThrowExceptionForHR(hr);
            }
            else if (renderer == Settings.VRenderers.VMR7)
            {
                IBaseFilter add_vmr = (IBaseFilter)new VideoMixingRenderer();
                hr = graphBuilder.AddFilter(add_vmr, "Video Renderer");
                DsError.ThrowExceptionForHR(hr);
            }
            else if (renderer == Settings.VRenderers.VMR9)
            {
                IBaseFilter add_vmr9 = (IBaseFilter)new VideoMixingRenderer9();
                hr = graphBuilder.AddFilter(add_vmr9, "Video Mixing Renderer 9");
                DsError.ThrowExceptionForHR(hr);
            }
            else if (renderer == Settings.VRenderers.EVR)
            {
                //Создаём Win32-окно, т.к. использовать WPF-поверхность не получится
                VHost = new VideoHwndHost();
                VHost.RepaintRequired += new EventHandler(VHost_RepaintRequired);
                VHostElement.Child = VHost;
                VHandle = VHost.Handle;

                //Добавляем и настраиваем EVR
                IBaseFilter add_evr = (IBaseFilter)new EnhancedVideoRenderer();
                hr = graphBuilder.AddFilter(add_evr, "Enhanced Video Renderer");
                DsError.ThrowExceptionForHR(hr);

                object obj;
                IMFGetService pGetService = null;
                pGetService = (IMFGetService)add_evr;
                hr = pGetService.GetService(MFServices.MR_VIDEO_RENDER_SERVICE, typeof(IMFVideoDisplayControl).GUID, out obj);
                MFError.ThrowExceptionForHR(hr);

                try
                {
                    EVRControl = (IMFVideoDisplayControl)obj;
                }
                catch
                {
                    Marshal.ReleaseComObject(obj);
                    throw;
                }

                //Указываем поверхность
                hr = EVRControl.SetVideoWindow(VHandle);
                MFError.ThrowExceptionForHR(hr);

                //Отключаем сохранение аспекта
                hr = EVRControl.SetAspectRatioMode(MFVideoAspectRatioMode.None);
                MFError.ThrowExceptionForHR(hr);
            }

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

            if (EVRControl == null)
            {
                //Ищем рендерер и отключаем соблюдение аспекта (аспект будет определяться размерами видео-окна)
                IBaseFilter filter = null;
                graphBuilder.FindFilterByName("Video Renderer", out filter);
                if (filter != null)
                {
                    IVMRAspectRatioControl vmr = filter as IVMRAspectRatioControl;
                    if (vmr != null) DsError.ThrowExceptionForHR(vmr.SetAspectRatioMode(VMRAspectRatioMode.None));
                }
                else
                {
                    graphBuilder.FindFilterByName("Video Mixing Renderer 9", out filter);
                    if (filter != null)
                    {
                        IVMRAspectRatioControl9 vmr9 = filter as IVMRAspectRatioControl9;
                        if (vmr9 != null) DsError.ThrowExceptionForHR(vmr9.SetAspectRatioMode(VMRAspectRatioMode.None));
                    }
                }
            }

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

            // Query for video interfaces, which may not be relevant for audio files
            this.videoWindow = (EVRControl == null) ? this.graphBuilder as IVideoWindow : null;
            this.basicVideo = (EVRControl == null) ? this.graphBuilder as IBasicVideo : null;

            // Query for audio interfaces, which may not be relevant for video-only files
            this.basicAudio = this.graphBuilder as IBasicAudio;
            basicAudio.put_Volume(-(int)(10000 - Math.Pow(Settings.VolumeLevel, 1.0 / 5) * 10000)); //Громкость для ДиректШоу

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

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

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

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

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

            this.Focus();

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

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

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

            //Запускаем таймер обновления позиции
            if (timer != null) timer.Start();
        }
Esempio n. 13
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);
                }
            }
        }
Esempio n. 14
0
        //Мотод для загрузки видео файла.
        public void FileLoad(string sfile, Panel vPanel)
        {
            CleanUp();

            graphBuilder  = (IGraphBuilder) new FilterGraph();
            mediaControl  = graphBuilder as IMediaControl;
            mediaPosition = graphBuilder as IMediaPosition;
            videoWindow   = graphBuilder as IVideoWindow;
            basicAudio    = graphBuilder as IBasicAudio;

            ddColor.lBrightness = 0;
            ddColor.lContrast = 0;
            ddColor.lGamma = 0;
            ddColor.lSaturation = 0;

            graphBuilder.RenderFile(sfile, null);
            videoWindow.put_Owner(vPanel.Handle);
            videoWindow.put_WindowStyle(WindowStyle.Child
                                      | WindowStyle.ClipSiblings
                                      | WindowStyle.ClipChildren);
            videoWindow.SetWindowPosition(vPanel.ClientRectangle.Left,
                                          vPanel.ClientRectangle.Top,
                                          vPanel.ClientRectangle.Width,
                                          vPanel.ClientRectangle.Height);

            mediaControl.Run();
            CurrentStatus = mStatus.Play;
            mediaPosition.get_Duration(out mediaTimeSeconds);
            allSeconds = (int)mediaTimeSeconds;
        }
Esempio n. 15
0
        private void StartCapture()
        {
            int hr;

            ISampleGrabber sampGrabber = null;
            IBaseFilter capFilter = null;
            ICaptureGraphBuilder2 capGraph = null;

            if (System.IO.File.Exists(txtAviFileName.Text))
            {
                // Get the graphbuilder object
                m_FilterGraph = (IFilterGraph2) new FilterGraph();
                m_mediaCtrl = m_FilterGraph as IMediaControl;

                // Get the ICaptureGraphBuilder2
                capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();

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

                // Start building the graph
                hr = capGraph.SetFiltergraph(m_FilterGraph);
                DsError.ThrowExceptionForHR(hr);

                // Add the video source
                hr = m_FilterGraph.AddSourceFilter(txtAviFileName.Text, "File Source (Async.)", out capFilter);
                DsError.ThrowExceptionForHR(hr);

                //add AVI Decompressor
                IBaseFilter pAVIDecompressor = (IBaseFilter) new AVIDec();
                hr = m_FilterGraph.AddFilter(pAVIDecompressor, "AVI Decompressor");
                DsError.ThrowExceptionForHR(hr);

                IBaseFilter ffdshow;
                try
                {
                    // Create Decoder filter COM object (ffdshow video decoder)
                    Type comtype = Type.GetTypeFromCLSID(new Guid("{04FE9017-F873-410E-871E-AB91661A4EF7}"));
                    if (comtype == null)
                        throw new NotSupportedException("Creating ffdshow video decoder COM object fails.");
                    object comobj = Activator.CreateInstance(comtype);
                    ffdshow = (IBaseFilter) comobj; // error ocurrs! raised exception
                    comobj = null;
                }
                catch
                {
                    CustomMessageBox.Show("Please install/reinstall ffdshow");
                    return;
                }

                hr = m_FilterGraph.AddFilter(ffdshow, "ffdshow");
                DsError.ThrowExceptionForHR(hr);

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

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


                IBaseFilter vidrender = (IBaseFilter) new VideoRenderer();
                hr = m_FilterGraph.AddFilter(vidrender, "Render");
                DsError.ThrowExceptionForHR(hr);


                IPin captpin = DsFindPin.ByDirection(capFilter, PinDirection.Output, 0);

                IPin ffdpinin = DsFindPin.ByName(ffdshow, "In");

                IPin ffdpinout = DsFindPin.ByName(ffdshow, "Out");

                IPin samppin = DsFindPin.ByName(baseGrabFlt, "Input");

                hr = m_FilterGraph.Connect(captpin, ffdpinin);
                DsError.ThrowExceptionForHR(hr);
                hr = m_FilterGraph.Connect(ffdpinout, samppin);
                DsError.ThrowExceptionForHR(hr);

                FileWriter filewritter = new FileWriter();
                IFileSinkFilter filemux = (IFileSinkFilter) filewritter;
                //filemux.SetFileName("test.avi",);

                //hr = capGraph.RenderStream(null, MediaType.Video, capFilter, null, vidrender);
                // DsError.ThrowExceptionForHR(hr); 

                SaveSizeInfo(sampGrabber);

                // setup buffer
                if (m_handle == IntPtr.Zero)
                    m_handle = Marshal.AllocCoTaskMem(m_stride*m_videoHeight);

                // tell the callback to ignore new images
                m_PictureReady = new ManualResetEvent(false);
                m_bGotOne = false;
                m_bRunning = false;

                timer1 = new Thread(timer);
                timer1.IsBackground = true;
                timer1.Start();

                m_mediaextseek = m_FilterGraph as IAMExtendedSeeking;
                m_mediapos = m_FilterGraph as IMediaPosition;
                m_mediaseek = m_FilterGraph as IMediaSeeking;
                double length = 0;
                m_mediapos.get_Duration(out length);
                trackBar_mediapos.Minimum = 0;
                trackBar_mediapos.Maximum = (int) length;

                Start();
            }
            else
            {
                MessageBox.Show("File does not exist");
            }
        }
        private void StartCapture()
        {
            int hr;

            ISampleGrabber        sampGrabber = null;
            IBaseFilter           capFilter   = null;
            ICaptureGraphBuilder2 capGraph    = null;

            if (System.IO.File.Exists(txtAviFileName.Text))
            {
                // Get the graphbuilder object
                m_FilterGraph = (IFilterGraph2) new FilterGraph();
                m_mediaCtrl   = m_FilterGraph as IMediaControl;

                // Get the ICaptureGraphBuilder2
                capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();

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

                // Start building the graph
                hr = capGraph.SetFiltergraph(m_FilterGraph);
                DsError.ThrowExceptionForHR(hr);

                // Add the video source
                hr = m_FilterGraph.AddSourceFilter(txtAviFileName.Text, "File Source (Async.)", out capFilter);
                DsError.ThrowExceptionForHR(hr);

                //add AVI Decompressor
                IBaseFilter pAVIDecompressor = (IBaseFilter) new AVIDec();
                hr = m_FilterGraph.AddFilter(pAVIDecompressor, "AVI Decompressor");
                DsError.ThrowExceptionForHR(hr);

                IBaseFilter ffdshow;
                try
                {
                    // Create Decoder filter COM object (ffdshow video decoder)
                    Type comtype = Type.GetTypeFromCLSID(new Guid("{04FE9017-F873-410E-871E-AB91661A4EF7}"));
                    if (comtype == null)
                    {
                        throw new NotSupportedException("Creating ffdshow video decoder COM object fails.");
                    }
                    object comobj = Activator.CreateInstance(comtype);
                    ffdshow = (IBaseFilter)comobj;  // error ocurrs! raised exception
                    comobj  = null;
                }
                catch
                {
                    CustomMessageBox.Show("Please install/reinstall ffdshow");
                    return;
                }

                hr = m_FilterGraph.AddFilter(ffdshow, "ffdshow");
                DsError.ThrowExceptionForHR(hr);

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

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


                IBaseFilter vidrender = (IBaseFilter) new VideoRenderer();
                hr = m_FilterGraph.AddFilter(vidrender, "Render");
                DsError.ThrowExceptionForHR(hr);


                IPin captpin = DsFindPin.ByDirection(capFilter, PinDirection.Output, 0);

                IPin ffdpinin = DsFindPin.ByName(ffdshow, "In");

                IPin ffdpinout = DsFindPin.ByName(ffdshow, "Out");

                IPin samppin = DsFindPin.ByName(baseGrabFlt, "Input");

                hr = m_FilterGraph.Connect(captpin, ffdpinin);
                DsError.ThrowExceptionForHR(hr);
                hr = m_FilterGraph.Connect(ffdpinout, samppin);
                DsError.ThrowExceptionForHR(hr);

                FileWriter      filewritter = new FileWriter();
                IFileSinkFilter filemux     = (IFileSinkFilter)filewritter;
                //filemux.SetFileName("test.avi",);

                //hr = capGraph.RenderStream(null, MediaType.Video, capFilter, null, vidrender);
                // DsError.ThrowExceptionForHR(hr);

                SaveSizeInfo(sampGrabber);

                // setup buffer
                if (m_handle == IntPtr.Zero)
                {
                    m_handle = Marshal.AllocCoTaskMem(m_stride * m_videoHeight);
                }

                // tell the callback to ignore new images
                m_PictureReady = new ManualResetEvent(false);
                m_bGotOne      = false;
                m_bRunning     = false;

                timer1 = new Thread(timer);
                timer1.IsBackground = true;
                timer1.Start();

                m_mediaextseek = m_FilterGraph as IAMExtendedSeeking;
                m_mediapos     = m_FilterGraph as IMediaPosition;
                m_mediaseek    = m_FilterGraph as IMediaSeeking;
                double length = 0;
                m_mediapos.get_Duration(out length);
                trackBar_mediapos.Minimum = 0;
                trackBar_mediapos.Maximum = (int)length;

                Start();
            }
            else
            {
                MessageBox.Show("File does not exist");
            }
        }
Esempio n. 17
0
        void Play(String fileName)
        {
            try
            {
                graphBuilder = (IGraphBuilder)new FilterGraph();
                mediaCtrl = (IMediaControl)graphBuilder;
                mediaEvt = (IMediaEventEx)graphBuilder;
                mediaPos = (IMediaPosition)graphBuilder;
                videoWin = (IVideoWindow)graphBuilder;

                pane.getInfo(InfoQueue, fileName);
                graphBuilder.RenderFile( fileName, null );

                videoWin.put_Owner(Video_panel.Handle);
                //videoWin.put_Owner(this.Handle);
                videoWin.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren);

                setWindow();
                mediaCtrl.Run();

                double total_time;
                mediaPos.get_Duration(out total_time);

                Video_timer.Enabled = true;
                iStatus = InfoStatus.Play;
                message_label.Width = 0;
                message_label.Height = 0;
            }
            catch (Exception)
            {
                MessageBox.Show("Couldn't start");
            }
        }