Ejemplo n.º 1
0
        private void SetupVideoWindow()
        {
            int hr = 0;

            //set the video window to be a child of the main window
            //putowner : Sets the owning parent window for the video playback window.
            hr = videoWindow.put_Owner(dejavuForm.pictureBx.Handle);
            DsError.ThrowExceptionForHR(hr);

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


            //Make the video window visible, now that it is properly positioned
            //put_visible : This method changes the visibility of the video window.
            hr = videoWindow.put_Visible(OABool.True);
            DsError.ThrowExceptionForHR(hr);

            hr = mediaControl.Run();

            DsError.ThrowExceptionForHR(hr);
            HandleGraphEvent();

            CurrentState = PlayState.Running;

            mainForm.ResumeSensor();
            //mainForm.WebCamControl_Resize(this, null);
            //videoControl.GetMaxAvailableFrameRate(pUSB.FindPin(""));
        }
Ejemplo n.º 2
0
        void SetupVideoWindow(IntPtr owner)
        {
            int hr;

            try
            {
                // Set the video window to be a child of the main window
                hr = videoWin.put_Owner(owner);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                // Set video window style
                hr = videoWin.put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                // Use helper function to position video window in client rect of owner window
                //ResizeVideoWindow();

                // Make the video window visible, now that it is properly positioned
                hr = videoWin.put_Visible(DsHlp.OATRUE);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }
            }
            catch (Exception ee)
            {
                //MessageBox.Show(this, "Could not setup video window\r\n" + ee.Message, "DirectShow.NET", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
Ejemplo n.º 3
0
        public void CloseInterfaces()
        {
            // Stop previewing data
            if (_mediaControl != null)
            {
                _mediaControl.StopWhenReady();
            }

            _currentState = PlayState.Stopped;

            // Stop receiving events
            if (_mediaEventEx != null)
            {
                _mediaEventEx.SetNotifyWindow(IntPtr.Zero, WmGraphnotify, IntPtr.Zero);
            }

            // Relinquish ownership (IMPORTANT!) of the video window.
            // Failing to call put_Owner can lead to assert failures within
            // the video renderer, as it still assumes that it has a valid
            // parent window.
            if (_videoWindow != null)
            {
                _videoWindow.put_Visible(OABool.False);
                _videoWindow.put_Owner(IntPtr.Zero);
            }

            // Remove filter graph from the running object table
            if (_rot != null)
            {
                _rot.Dispose();
                _rot = null;
            }

            // Release DirectShow interfaces
            if (_mediaControl != null)
            {
                Marshal.ReleaseComObject(_mediaControl);
            }
            _mediaControl = null;
            if (_mediaEventEx != null)
            {
                Marshal.ReleaseComObject(_mediaEventEx);
            }
            _mediaEventEx = null;
            if (_videoWindow != null)
            {
                Marshal.ReleaseComObject(_videoWindow);
            }
            _videoWindow = null;
            Marshal.ReleaseComObject(_graphBuilder);
            _graphBuilder = null;
            Marshal.ReleaseComObject(_captureGraphBuilder);
            _captureGraphBuilder = null;
        }
Ejemplo n.º 4
0
        //COMやインタフェースの解放を行う
        public void CloseInterfaces()
        {
            try
            {
                if (mediaControl != null)
                {
                    mediaControl.Stop();
                    Thread.Sleep(100);
                    mediaControl = null;
                }

                if (mediaEvent != null)
                {
                    mediaEvent.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
                    mediaEvent = null;
                }

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

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

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

                if (mVideoChecker != null)
                {
                    mVideoChecker.CloseInterfaces();
                    mVideoChecker = null;
                }
                //if (mAudioChecker != null)
                //{
                //	mAudioChecker.CloseInterfaces();
                //	mAudioChecker = null;
                //}
            }
            catch (Exception e)
            {
                SMMMessageBox.Show("エラー:インタフェースの終了に失敗しました。Error: An error ocouured when closing video interface. " + e.ToString(), SMMMessageBoxIcon.Error);
            }
        }
Ejemplo n.º 5
0
        public override void Process()
        {
            if (!Playing)
            {
                return;
            }
            if (!m_bStarted)
            {
                return;
            }
            if (GUIGraphicsContext.InVmr9Render)
            {
                return;
            }
            TimeSpan ts = DateTime.Now - updateTimer;

            if (ts.TotalMilliseconds >= 800 || m_speedRate != 1)
            {
                UpdateCurrentPosition();
                updateTimer = DateTime.Now;
                if (GUIGraphicsContext.BlankScreen ||
                    (GUIGraphicsContext.Overlay == false && GUIGraphicsContext.IsFullScreenVideo == false))
                {
                    if (m_bVisible)
                    {
                        m_bVisible = false;
                        if (videoWin != null)
                        {
                            videoWin.put_Visible(OABool.False);
                        }
                    }
                }
                else if (!m_bVisible)
                {
                    m_bVisible = true;
                    if (videoWin != null)
                    {
                        videoWin.put_Visible(OABool.True);
                    }
                }
                CheckVideoResolutionChanges();
                updateTimer = DateTime.Now;
            }
            if (m_speedRate != 1)
            {
                DoFFRW();
            }
            OnProcess();
        }
Ejemplo n.º 6
0
        // Set the video window within the control specified by hControl
        private void ConfigVideoWindow(Control hControl)
        {
            int hr;

            IVideoWindow ivw = m_FilterGraph as IVideoWindow;

            // Set the parent
            hr = ivw.put_Owner(hControl == null?(IntPtr)0:hControl.Handle);
            DsError.ThrowExceptionForHR(hr);
            // Turn off captions, etc
            hr = ivw.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings);
            DsError.ThrowExceptionForHR(hr);


            // Yes, make it visible
            if (hControl == null)
            {
                hr = ivw.put_Visible(OABool.False);
                ivw.put_AutoShow(OABool.False);
            }
            else
            {
                hr = ivw.put_Visible(OABool.True);
            }
            DsError.ThrowExceptionForHR(hr);

            if (hControl != null)
            {
                // Move to upper left corner
                Rectangle rc = hControl.ClientRectangle;
                hr = ivw.SetWindowPosition(0, 0, rc.Right, rc.Bottom);
                DsError.ThrowExceptionForHR(hr);
            }
            else
            {
                // move outside the desktop
                Screen[] screens = Screen.AllScreens;
                int      h       = 0;
                for (int i = 0; i < screens.Length; i++)
                {
                    Screen screen = screens[i];
                    h = Math.Max(h, screen.Bounds.Bottom + 10);
                }
                Rectangle rc = new Rectangle(0, h, 1, 1);
                hr = ivw.SetWindowPosition(0, 0, rc.Right, rc.Bottom);
                DsError.ThrowExceptionForHR(hr);
            }
        }
Ejemplo n.º 7
0
        /// <summary> make the video preview window to show in videoPanel. </summary>
        bool SetupVideoWindow()
        {
            int hr;

            try
            {
                // Set the video window to be a child of the main window

                HwndSource hwndSource = PresentationSource.FromVisual(OwnerWindow) as HwndSource;



                hr = videoWin.put_Owner(hwndSource.Handle);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                // Set video window style
                hr = videoWin.put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                // Use helper function to position video window in client rect of owner window
                ResizeVideoWindow();

                // Make the video window visible, now that it is properly positioned
                hr = videoWin.put_Visible(DsHlp.OATRUE);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                hr = mediaEvt.SetNotifyWindow(hwndSource.Handle, WM_GRAPHNOTIFY, IntPtr.Zero);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }
                return(true);
            }
            catch (Exception ee)
            {
                System.Windows.Forms.MessageBox.Show("Could not setup video window\r\n" + ee.Message, "DirectShow.NET", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return(false);
            }
        }
        protected int SetVideoWindow()
        {
            int hr;

            videoWindow = (IVideoWindow)m_graphBuilder;
            if (videoWindow == null)
            {
                return(0);
            }

            //Set the owener of the videoWindow to an IntPtr of some sort (the Handle of any control - could be a form / button etc.)
            hr = videoWindow.put_Owner(m_panel.Handle);
            DsError.ThrowExceptionForHR(hr);

            //Set the style of the video window
            hr = videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren);
            DsError.ThrowExceptionForHR(hr);

            hr = videoWindow.put_MessageDrain(m_panel.Handle);


            // Position video window in client rect of main application window
            hr = videoWindow.SetWindowPosition(0, 0, m_panel.Width, m_panel.Height);
            DsError.ThrowExceptionForHR(hr);

            // Make the video window visible
            hr = videoWindow.put_Visible(OABool.True);
            DsError.ThrowExceptionForHR(hr);

            return(hr);
        }
Ejemplo n.º 9
0
    private void ShowVideoWindow(Control hControl)
    {
        int hr;
        // get the video window from the graph
        IVideoWindow videoWindow = (DirectShowLib.IVideoWindow)m_graphBuilder;

        //IBasicVideo basicFilter = (IBasicVideo) m_graphBuilder;
        //basicFilter.put_DestinationWidth(320);
        //basicFilter.put_DestinationHeight(240);

        // Set the owener of the videoWindow to an IntPtr of some sort (the Handle of any control - could be a form / button etc.)
        hr = videoWindow.put_Owner(hControl.Handle);
        DsError.ThrowExceptionForHR(hr);

        // Set the style of the video window
        hr = videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren);
        DsError.ThrowExceptionForHR(hr);

        // Position video window in client rect of main application window
        hr = videoWindow.SetWindowPosition(0, 0, hControl.Width, hControl.Height);
        DsError.ThrowExceptionForHR(hr);

        // Make the video window visible
        hr = videoWindow.put_Visible(OABool.True);
        DsError.ThrowExceptionForHR(hr);

        Start();
    }
Ejemplo n.º 10
0
        public void Initialize()
        {
            _graphBuilder = (IGraphBuilder) new FilterGraph();

            _filterCamera = new DSFilter(new VirtualCamFilter());
            _graphBuilder.AddFilter(_filterCamera.Value, "Virtual Camera");

            //_filterCamera.Pins[0].Direction = PinDirection.

            //_filterVMR9Renderer = new DSFilter(new Guid("51B4ABF3-748F-4E3B-A276-C828330E926A"));
            //_graphBuilder.AddFilter(_filterVMR9Renderer.Value, "Renderer");

            _filterYUV = new DSFilter(new Guid("B179A682-641B-11D2-A4D9-0060080BA634"));
            _graphBuilder.AddFilter(_filterYUV.Value, "YUV");

            //_filterH264Encoder = new DSFilter(new Guid("3FD83588-D403-40A2-9739-5F75E1590AB8"));
            _filterH264Encoder = new DSFilter(new H264EncoderFilter());
            _graphBuilder.AddFilter(_filterH264Encoder.Value, "H264 En");

            //_filterNullRenderer = new DSFilter(new Guid("C1F400A4-3F08-11D3-9F0B-006008039E37"));
            //_graphBuilder.AddFilter(_filterNullRenderer.Value, "Null");

            _filterRTSPServer = new DSFilter(new Guid("EABF2C99-F9AD-43CD-8108-109D4E9FADC5"));
            _graphBuilder.AddFilter(_filterRTSPServer.Value, "RTSP Server");

            // Camera -> RGB2YUV -> H264 -> RTSP
            _filterCamera.OutputPin.ConnectDirect(_filterYUV.InputPin);
            _filterYUV.OutputPin.ConnectDirect(_filterH264Encoder.InputPin);
            _filterH264Encoder.OutputPin.ConnectDirect(_filterRTSPServer.InputPin);

            m_MediaControl = (IMediaControl)_graphBuilder;
            m_VideoWindow  = (IVideoWindow)_graphBuilder;

            m_VideoWindow.put_Visible(0);
        }
Ejemplo n.º 11
0
 public void Stop()
 {
     if (_parentControl != null)
     {
         _parentControl.SizeChanged -= _parentControl_SizeChanged;
     }
     if (_videoWin != null)
     {
         _videoWin.put_Visible(OABool.False);
         _videoWin = null;
     }
     if (_mediaCtrl != null)
     {
         _mediaCtrl.Stop();
         _mediaCtrl = null;
     }
     if (_rotEntry != null)
     {
         _rotEntry.Dispose();
         _rotEntry = null;
     }
     if (_graphBuilder != null)
     {
         DirectShowUtil.ReleaseComObject(_graphBuilder, 2000);
         _graphBuilder = null;
     }
 }
Ejemplo n.º 12
0
        // Set the video window within the control specified by hControl
        private void ConfigVideoWindow(Control hControl)
        {
            int hr;

            IVideoWindow ivw = m_FilterGraph as IVideoWindow;

            // Set the parent
            try
            {
                hr = ivw.put_Owner(hControl.Handle);
            }
            catch
            {
            }

            //DsError.ThrowExceptionForHR( hr );

            // Turn off captions, etc
            hr = ivw.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings);
            //DsError.ThrowExceptionForHR( hr );

            // Yes, make it visible
            hr = ivw.put_Visible(OABool.False);
            //DsError.ThrowExceptionForHR( hr );

            // Move to upper left corner
            //Rectangle rc = hControl.ClientRectangle;
            //hr = ivw.SetWindowPosition( 0, 0, rc.Right, rc.Bottom );
            //DsError.ThrowExceptionForHR( hr );
        }
Ejemplo n.º 13
0
        // Configure the video window
        private void ConfigureVideoWindow(IVideoWindow videoWindow, Control hWin)
        {
            int hr;

            // Set the output window
            hr = videoWindow.put_Owner(hWin.Handle);
            DsError.ThrowExceptionForHR(hr);

            // Set the window style
            hr = videoWindow.put_WindowStyle((DirectShowLib.WindowStyle.Child | DirectShowLib.WindowStyle.ClipSiblings));
            DsError.ThrowExceptionForHR(hr);

            // Make the window visible
            hr = videoWindow.put_Visible(OABool.True);
            DsError.ThrowExceptionForHR(hr);

            // Position the playing location
            Rectangle rc = hWin.ClientRectangle;

            hr = videoWindow.SetWindowPosition(0, 0, rc.Right, rc.Bottom);
            DsError.ThrowExceptionForHR(hr);

            hr = videoWindow.put_MessageDrain(hWin.Handle);
            DsError.ThrowExceptionForHR(hr);
        }
Ejemplo n.º 14
0
        public void CloseInterfaces()
        {
            if (mediaControl != null)
            {
                int hr = mediaControl.StopWhenReady();
                DsError.ThrowExceptionForHR(hr);
            }

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

            // Remove filter graph from the running object table.
            if (rot != null)
            {
                rot.Dispose();
                rot = null;
            }

            // Release DirectShow interfaces.
            Marshal.ReleaseComObject(this.mediaControl); this.mediaControl = null;
            Marshal.ReleaseComObject(this.videoWindow); this.videoWindow   = null;
            Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null;
            Marshal.ReleaseComObject(this.captureGraphBuilder); this.captureGraphBuilder = null;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Configures our "dummy" IVideoWindow to work well
        /// with our interactive menus and to make sure the
        /// window remains hidden from view.
        /// </summary>
        private void ConfigureDummyWindow()
        {
            /* We want to hide our dummy renderer window */
            int hr = m_dummyRenderWindow.put_WindowState(WindowState.Hide);

            DsError.ThrowExceptionForHR(hr);

            WindowStyle windowStyle;

            /* Get the current style of the window */
            m_dummyRenderWindow.get_WindowStyle(out windowStyle);
            DsError.ThrowExceptionForHR(hr);

            /* Remove these styles using bitwise magic */
            windowStyle &= ~WindowStyle.SysMenu;
            windowStyle &= ~WindowStyle.Caption;
            windowStyle &= ~WindowStyle.Border;

            /* Change the window to our new style */
            hr = m_dummyRenderWindow.put_WindowStyle(windowStyle);
            DsError.ThrowExceptionForHR(hr);

            /* This should hide the window from view */
            hr = m_dummyRenderWindow.put_Visible(OABool.False);
            DsError.ThrowExceptionForHR(hr);

            /* Turn off auto show, so the renderer doesn't try to show itself */
            hr = m_dummyRenderWindow.put_AutoShow(OABool.False);
            DsError.ThrowExceptionForHR(hr);
        }
Ejemplo n.º 16
0
        /// <summary>
        ///  Disconnect and remove all filters except the device
        ///  and compressor filters. This is the opposite of
        ///  renderGraph(). Soem properties such as FrameRate
        ///  can only be set when the device output pins are not
        ///  connected.
        /// </summary>
        void DerenderGraph()
        {
            // Stop the graph if it is running (ignore errors)
            _mediaControl?.Stop();

            // Free the preview window (ignore errors)
            if (_videoWindow != null)
            {
                _videoWindow.put_Visible(OABool.False);
                _videoWindow.put_Owner(IntPtr.Zero);
                _videoWindow = null;
            }

            if ((int)_actualGraphState < (int)GraphState.Rendered)
            {
                return;
            }

            // Update the state
            _actualGraphState  = GraphState.Created;
            _isPreviewRendered = false;

            // Disconnect all filters downstream of the
            // video and audio devices. If we have a compressor
            // then disconnect it, but don't remove it
            if (_videoDeviceFilter != null)
            {
                RemoveDownstream(_videoDeviceFilter);
            }
        }
Ejemplo n.º 17
0
        public HRESULT Dispose()
        {
            try
            {
                m_MediaControl.Stop();
                m_VideoWindow.put_Visible(0);

                m_MediaControl = null;
                m_VideoWindow  = null;

                if (_graphBuilder != null)
                {
                    _graphBuilder.RemoveFilter(_filterCamera.Value);
                    _graphBuilder.RemoveFilter(_filterVMR9Renderer.Value);

                    _filterCamera.Dispose();
                    _filterVMR9Renderer.Dispose();

                    _filterVMR9Renderer = null;
                    _filterCamera       = null;

                    Marshal.ReleaseComObject(_graphBuilder);
                    _graphBuilder = null;
                }
                GC.Collect();

                return(COMHelper.NOERROR);
            }
            catch
            {
                return(COMHelper.E_FAIL);
            }
        }
Ejemplo n.º 18
0
        private void killOutput()
        {
            IVideoWindow videoWindow = this.getVideoWindow();

            videoWindow.put_Visible(OABool.False);
            videoWindow.put_Owner(IntPtr.Zero);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Configure the video window
        /// </summary>
        /// <param name="videoWindow">Interface of the video renderer</param>
        /// <param name="previewControl">Preview Control to draw into</param>
        private void ConfigureVideoWindow(IVideoWindow videoWindow, Control previewControl)
        {
            int hr;

            if (previewControl == null)
            {
                return;
            }

            // Set the output window
            hr = videoWindow.put_Owner(ThreadSafe.GetHandle(previewControl));
            if (hr >= 0) // If there is video
            {
                // Set the window style
                hr = videoWindow.put_WindowStyle((WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings));
                DsError.ThrowExceptionForHR(hr);

                // Make the window visible
                hr = videoWindow.put_Visible(OABool.True);
                DsError.ThrowExceptionForHR(hr);

                // Position the playing location
                Rectangle rc = ThreadSafe.GetClientRectangle(previewControl);
                hr = videoWindow.SetWindowPosition(0, 0, rc.Right, rc.Bottom);
                DsError.ThrowExceptionForHR(hr);
            }
        }
Ejemplo n.º 20
0
        void InitVideoWidnow(IntPtr handle)
        {
            var hr = videoWindow.put_Owner(handle);

            DsError.ThrowExceptionForHR(hr);

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

            hr = videoWindow.put_MessageDrain(handle);
            DsError.ThrowExceptionForHR(hr);

            UpdateVideoSize();

            hr = videoWindow.put_Visible(OABool.True);
            DsError.ThrowExceptionForHR(hr);
        }
Ejemplo n.º 21
0
        /// <summary> make the video preview window to show in videoPanel. </summary>
        bool SetupVideoWindow()
        {
            int hr;

            try
            {
                // Set the video window to be a child of the main window
                hr = videoWin.put_Owner(videoPanel.Handle);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                // Set video window style
                hr = videoWin.put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                // Use helper function to position video window in client rect of owner window
                ResizeVideoWindow();

                // Make the video window visible, now that it is properly positioned
                hr = videoWin.put_Visible(DsHlp.OATRUE);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                hr = mediaEvt.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }
                return(true);
            }
            catch (Exception ee)
            {
                MessageBox.Show(this, "Could not setup video window\r\n" + ee.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return(false);
            }
        }
Ejemplo n.º 22
0
        /// <summary> make the video preview window to show in videoPanel. </summary>
        private bool SetupVideoWindow()
        {
            int hr;

            try {
                // Set the video window to be a child of the main window
                //hr = videoWin.put_Owner(videoPanel.Handle);
                //if (hr < 0)
                //    Marshal.ThrowExceptionForHR(hr);

                // Set video window style
                hr = videoWin.put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                // Use helper function to position video window in client rect of owner window
                //ResizeVideoWindow();

                // Make the video window visible, now that it is properly positioned
                hr = videoWin.put_Visible(DsHlp.OAFALSE);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                hr = videoWin.put_AutoShow(DsHlp.OAFALSE);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                //hr = mediaEvt.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero);
                //if (hr < 0)
                //    Marshal.ThrowExceptionForHR(hr);
                return(true);
            }
            catch (Exception ee) {
                return(false);
            }
        }
Ejemplo n.º 23
0
        /// <summary>Attach this video to a window</summary>
        public void AttachToWindow(IntPtr handle)
        {
            if (m_video_window == null)
            {
                return;
            }

            if (handle != IntPtr.Zero)
            {
                DsError.ThrowExceptionForHR(m_video_window.put_Owner(handle));                                                                        // Parent the window
                DsError.ThrowExceptionForHR(m_video_window.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings)); // Set the window style
                DsError.ThrowExceptionForHR(m_video_window.put_MessageDrain(handle));                                                                 // Set the destination for messages
                DsError.ThrowExceptionForHR(m_video_window.put_Visible(OABool.True));                                                                 // Make the window visible
            }
            else
            {
                DsError.ThrowExceptionForHR(m_video_window.put_Visible(OABool.False));               // Make the window invisible
                DsError.ThrowExceptionForHR(m_video_window.put_MessageDrain(handle));                // Set the destination for messages
                DsError.ThrowExceptionForHR(m_video_window.put_Owner(handle));                       // Unparent it
            }
        }
Ejemplo n.º 24
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);
     }
 }
Ejemplo n.º 25
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 2) // Catch WM_Destroy to reassign the VideoWindow owner
            {
                if (_detachedWindow == null && _vw != null)
                {
                    // The EVR easily handles this, but VMR7 and VMR9 parent windows have to be reset
                    // when they lose the Handle.
                    _vw.put_Visible(OABool.False);
                    _vw.put_Owner(IntPtr.Zero);
                }
                _handleLost = true;
            }

            base.WndProc(ref m);

            if (m.Msg == 1)
            {
                if (_handleLost)
                {
                    if (_detachedWindow == null)
                    {
                        // the window handle was lost (probably due to docking).  Reinit with the new handle
                        _isInit = false;
                        InitVideoWindow(this.Handle);
                        if (_vw != null)
                        {
                            _vw.put_Visible(OABool.True);
                        }
                    }
                    _handleLost = false;
                }
            }

            if (m.Msg == 0x203) //WM_LBUTTONDBLCLK
            {
                this.VideoInternalWindow_DoubleClick(this, new EventArgs());
            }
        }
Ejemplo n.º 26
0
        protected override void CloseInterfaces()
        {
            if (VideoWindow != null)
            {
                VideoWindow.put_Visible(DsHlp.OAFALSE);
                VideoWindow.put_MessageDrain(IntPtr.Zero);
                VideoWindow.put_Owner(IntPtr.Zero);
                VideoWindow = null;
            }

            BasicVideo2 = null;     // both interfaces are going to be released when _pGraphBuilder is released

            base.CloseInterfaces(); // must be called to release the main pointer and all child interfaces (if any)
        }
Ejemplo n.º 27
0
        ////////////////
        /// Get/Put Visible
        private void TestVisible()
        {
            int    hr;
            OABool Visible1, Visible2;

            // Read the current value
            hr = m_ivw.get_Visible(out Visible1);
            Marshal.ThrowExceptionForHR(hr);

            // Flip it
            hr = m_ivw.put_Visible(~Visible1);
            Marshal.ThrowExceptionForHR(hr);

            // Re-read
            hr = m_ivw.get_Visible(out Visible2);
            Marshal.ThrowExceptionForHR(hr);

            // Make sure the value we set is what we just read
            Debug.Assert(Visible1 != Visible2, "Put/Get Visible");

            // Try it the other way

            // Read the current value
            hr = m_ivw.get_Visible(out Visible1);
            Marshal.ThrowExceptionForHR(hr);

            // Flip it
            hr = m_ivw.put_Visible(~Visible1);
            Marshal.ThrowExceptionForHR(hr);

            // Re-read
            hr = m_ivw.get_Visible(out Visible2);
            Marshal.ThrowExceptionForHR(hr);

            // Make sure the value we set is what we just read
            Debug.Assert(Visible1 != Visible2, "Put/Get Visible");
        }
Ejemplo n.º 28
0
        private void RenderToPanel(Panel panel, IntPtr notifyWindow)
        {
            int hr;

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

            // Set the video window to be a child of the panel
            hr = videoWindow.put_Owner(panel.Handle);
            DsError.ThrowExceptionForHR(hr);

            // Set video window style
            hr = videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren);
            DsError.ThrowExceptionForHR(hr);

            // Position video window in client rect of panel
            hr = videoWindow.SetWindowPosition(0, 0, panel.Width, panel.Height);
            DsError.ThrowExceptionForHR(hr);

            // Make the video window visible, now that it is properly positioned
            hr = videoWindow.put_Visible(OABool.True);
            DsError.ThrowExceptionForHR(hr);
        }
Ejemplo n.º 29
0
        public void constrainOutputToPanel(System.Windows.Forms.Panel panel)
        {
            IVideoWindow videoWindow = this.getVideoWindow();

            videoWindow.put_Owner(panel.Handle);
            videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings);
            videoWindow.SetWindowPosition(
                panel.ClientRectangle.Left,
                panel.ClientRectangle.Top,
                panel.ClientRectangle.Width,
                panel.ClientRectangle.Height
                );
            videoWindow.put_MessageDrain(panel.Handle);
            videoWindow.put_Visible(OABool.True);
        }
Ejemplo n.º 30
0
        protected void derenderGraph()
        {
            // Stop the graph if it is running (ignore errors)
            if (mediaControl != null)
            {
                mediaControl.Stop();
            }

            // Free the preview window (ignore errors)
            if (videoWindow != null)
            {
                videoWindow.put_Visible(DsHlp.OAFALSE);
                videoWindow.put_Owner(IntPtr.Zero);
                videoWindow = null;
            }

            // Remove the Resize event handler
            if (PreviewWindow != null)
            {
                previewWindow.Resize -= new EventHandler(onPreviewWindowResize);
            }

            if ((int)graphState >= (int)GraphState.Rendered)
            {
                // Update the state
                graphState        = GraphState.Created;
                isCaptureRendered = false;
                isPreviewRendered = false;

                // Disconnect all filters downstream of the
                // video and audio devices. If we have a compressor
                // then disconnect it, but don't remove it
                if (videoDeviceFilter != null)
                {
                    removeDownstream(videoDeviceFilter, (videoCompressor == null));
                }
                if (audioDeviceFilter != null)
                {
                    removeDownstream(audioDeviceFilter, (audioCompressor == null));
                }

                // These filters should have been removed by the
                // calls above. (Is there anyway to check?)
                muxFilter        = null;
                fileWriterFilter = null;
            }
        }
        // Configure the video window
        private void ConfigureVideoWindow(IVideoWindow videoWindow, Control hWin)
        {
            int hr;

            // Set the output window
            hr = videoWindow.put_Owner(hWin.Handle);
            DsError.ThrowExceptionForHR(hr);

            // Set the window style
            hr = videoWindow.put_WindowStyle((WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings));
            DsError.ThrowExceptionForHR(hr);

            // Make the window visible
            hr = videoWindow.put_Visible(OABool.True);
            DsError.ThrowExceptionForHR(hr);

            // Position the playing location
            Rectangle rc = hWin.ClientRectangle;
            hr = videoWindow.SetWindowPosition(0, 0, rc.Right, rc.Bottom);
            DsError.ThrowExceptionForHR(hr);
        }
Ejemplo n.º 32
0
    private void Cleanup()
    {
      if (graphBuilder == null)
      {
        return;
      }
      int hr;
      Log.Info("RTSPPlayer:cleanup DShow graph");
      try
      {
        if (VMR9Util.g_vmr9 != null)
        {
          VMR9Util.g_vmr9.Vmr9MediaCtrl(_mediaCtrl);
          VMR9Util.g_vmr9.Enable(false);
        }

        if (mediaEvt != null)
        {
          hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
        }

        videoWin = graphBuilder as IVideoWindow;
        if (videoWin != null && GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR)
        {
          videoWin.put_Owner(IntPtr.Zero);
          videoWin.put_Visible(OABool.False);
        }

        _mediaCtrl = null;
        mediaEvt = null;
        _mediaSeeking = null;
        mediaPos = null;
        basicAudio = null;
        basicVideo = null;
        videoWin = null;
        SubEngine.GetInstance().FreeSubtitles();

        if (graphBuilder != null)
        {
          DirectShowUtil.RemoveFilters(graphBuilder);
          if (_rotEntry != null)
          {
            _rotEntry.SafeDispose();
            _rotEntry = null;
          }
          DirectShowUtil.FinalReleaseComObject(graphBuilder);
          graphBuilder = null;
        }

        if (VMR9Util.g_vmr9 != null)
        {
          VMR9Util.g_vmr9.SafeDispose();
          VMR9Util.g_vmr9 = null;
        }

        GUIGraphicsContext.form.Invalidate(true);
        _state = PlayState.Init;

        if (_mpegDemux != null)
        {
          Log.Info("cleanup mpegdemux");
          DirectShowUtil.FinalReleaseComObject(_mpegDemux);
          _mpegDemux = null;
        }
        if (_rtspSource != null)
        {
          Log.Info("cleanup _rtspSource");
          DirectShowUtil.FinalReleaseComObject(_rtspSource);
          _rtspSource = null;
        }
        if (_subtitleFilter != null)
        {
          DirectShowUtil.FinalReleaseComObject(_subtitleFilter);
          _subtitleFilter = null;
          if (this.dvbSubRenderer != null)
          {
            this.dvbSubRenderer.SetPlayer(null);
          }
          this.dvbSubRenderer = null;
        }


        if (vobSub != null)
        {
          Log.Info("cleanup vobSub");
          DirectShowUtil.FinalReleaseComObject(vobSub);
          vobSub = null;
        }
      }
      catch (Exception ex)
      {
        Log.Error("RTSPPlayer: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace);
      }

      //switch back to directx windowed mode
      Log.Info("RTSPPlayer: Disabling DX9 exclusive mode");
      GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null);
      GUIWindowManager.SendMessage(msg);
    }
Ejemplo n.º 33
0
        private void InitVideoWindow()
        {
            if (Render == null)
                return;

            videoWindow = (IVideoWindow)graphBuilder;

            //Set the owener of the videoWindow to an IntPtr of some sort (the Handle of any control - could be a form / button etc.)
            var hr = videoWindow.put_Owner(Render.Handle);
            DsError.ThrowExceptionForHR(hr);
            //Set the style of the video window
            hr = videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings);
            DsError.ThrowExceptionForHR(hr);

            // Position video window in client rect of main application window
            //hr = videoWindow.SetWindowPosition(0, 0, Render.Width, Render.Height);
            Resize();
            DsError.ThrowExceptionForHR(hr);
            videoWindow.put_Visible(OABool.True);
            Render.SizeChanged -= new EventHandler(onResize);
            Render.SizeChanged += new EventHandler(onResize);
        }
Ejemplo n.º 34
0
    public bool Play(string fileName, Form form)
    {
      fileName += ".tsbuffer";
      Log.WriteFile("play:{0}", fileName);
      _graphBuilder = (IFilterGraph2)new FilterGraph();
      _rotEntry = new DsROTEntry(_graphBuilder);


      Log.WriteFile("add tsfilesource");
      _tsFileSource = new TsFileSource();
      _graphBuilder.AddFilter((IBaseFilter)_tsFileSource, "TsFileSource");

      #region add mpeg-2 demux filter

      Log.WriteFile("add mpeg-2 demux");
      MPEG2Demultiplexer demux = new MPEG2Demultiplexer();
      _mpegDemux = (IBaseFilter)demux;
      int hr = _graphBuilder.AddFilter(_mpegDemux, "MPEG-2 Demultiplexer");

      #endregion

      #region create mpeg2 demux pins

      Log.WriteFile("create mpeg-2 demux pins");
      //create mpeg-2 demux output pins
      IMpeg2Demultiplexer demuxer = _mpegDemux as IMpeg2Demultiplexer;


      if (demuxer != null)
        hr = demuxer.CreateOutputPin(GetAudioMpg2Media(), "Audio", out _pinAudio);
      if (hr != 0)
      {
        Log.WriteFile("unable to create audio pin");
        return false;
      }
      if (demuxer != null)
        hr = demuxer.CreateOutputPin(GetVideoMpg2Media(), "Video", out _pinVideo);
      if (hr != 0)
      {
        Log.WriteFile("unable to create video pin");
        return false;
      }

      #endregion

      #region load file in tsfilesource

      Log.WriteFile("load file in tsfilesource");
      IFileSourceFilter interfaceFile = (IFileSourceFilter)_tsFileSource;
      if (interfaceFile == null)
      {
        Log.WriteFile("TSStreamBufferPlayer9:Failed to get IFileSourceFilter");
        return false;
      }

      AMMediaType mpeg2ProgramStream = new AMMediaType();
      mpeg2ProgramStream.majorType = MediaType.Stream;
      mpeg2ProgramStream.subType = MediaSubType.Mpeg2Program;

      mpeg2ProgramStream.unkPtr = IntPtr.Zero;
      mpeg2ProgramStream.sampleSize = 0;
      mpeg2ProgramStream.temporalCompression = false;
      mpeg2ProgramStream.fixedSizeSamples = true;
      mpeg2ProgramStream.formatType = FormatType.None;
      mpeg2ProgramStream.formatSize = 0;
      mpeg2ProgramStream.formatPtr = IntPtr.Zero;
      hr = interfaceFile.Load(fileName, mpeg2ProgramStream);

      if (hr != 0)
      {
        Log.WriteFile("TSStreamBufferPlayer9:Failed to load file");
        return false;
      }

      #region connect tsfilesource->demux

      Log.WriteFile("connect tsfilesource->demux");
      Log.WriteFile("TSStreamBufferPlayer9:connect tsfilesource->mpeg2 demux");
      IPin pinTsOut = DsFindPin.ByDirection((IBaseFilter)_tsFileSource, PinDirection.Output, 0);
      if (pinTsOut == null)
      {
        Log.WriteFile("TSStreamBufferPlayer9:failed to find output pin of tsfilesource");
        return false;
      }
      IPin pinDemuxIn = DsFindPin.ByDirection(_mpegDemux, PinDirection.Input, 0);
      if (pinDemuxIn == null)
      {
        Log.WriteFile("TSStreamBufferPlayer9:failed to find output pin of tsfilesource");
        return false;
      }

      hr = _graphBuilder.Connect(pinTsOut, pinDemuxIn);
      if (hr != 0)
      {
        Log.WriteFile("TSStreamBufferPlayer9:failed to connect tsfilesource->mpeg2 demux:{0:X}", hr);
        return false;
      }
      Release.ComObject(pinTsOut);
      Release.ComObject(pinDemuxIn);

      #endregion

      #region map demux pids

      Log.WriteFile("map mpeg2 pids");
      IMPEG2StreamIdMap pStreamId = (IMPEG2StreamIdMap)_pinVideo;
      hr = pStreamId.MapStreamId(0xe0, MPEG2Program.ElementaryStream, 0, 0);
      if (hr != 0)
      {
        Log.WriteFile("TSStreamBufferPlayer9: failed to map pid 0xe0->video pin");
        return false;
      }
      pStreamId = (IMPEG2StreamIdMap)_pinAudio;
      hr = pStreamId.MapStreamId(0xc0, MPEG2Program.ElementaryStream, 0, 0);
      if (hr != 0)
      {
        Log.WriteFile("TSStreamBufferPlayer9: failed  to map pid 0xc0->audio pin");
        return false;
      }

      #endregion

      #region render demux audio/video pins

      Log.WriteFile("render pins");
      hr = _graphBuilder.Render(_pinAudio);
      if (hr != 0)
      {
        Log.WriteFile("TSStreamBufferPlayer9:failed to render video output pin:{0:X}", hr);
      }

      hr = _graphBuilder.Render(_pinVideo);
      if (hr != 0)
      {
        Log.WriteFile("TSStreamBufferPlayer9:failed to render audio output pin:{0:X}", hr);
      }

      #endregion

      #endregion

      _videoWin = _graphBuilder as IVideoWindow;
      if (_videoWin != null)
      {
        _videoWin.put_Visible(OABool.True);
        _videoWin.put_Owner(form.Handle);
        _videoWin.put_WindowStyle(
          (WindowStyle)((int)WindowStyle.Child + (int)WindowStyle.ClipSiblings + (int)WindowStyle.ClipChildren));
        _videoWin.put_MessageDrain(form.Handle);
        _videoWin.SetWindowPosition(190, 250, 150, 150);
      }

      Log.WriteFile("run graph");
      _mediaCtrl = (IMediaControl)_graphBuilder;
      hr = _mediaCtrl.Run();
      Log.WriteFile("TSStreamBufferPlayer9:running:{0:X}", hr);

      return true;
    }
Ejemplo n.º 35
0
		/// <summary>
		///  Connects the filters of a previously created graph 
		///  (created by createGraph()). Once rendered the graph
		///  is ready to be used. This method may also destroy
		///  streams if we have streams we no longer want.
		/// </summary>
		protected void renderGraph()
		{
			Guid					cat;
			Guid					med;
			int						hr;
			bool					didSomething = false;
			const int WS_CHILD			= 0x40000000;	
			const int WS_CLIPCHILDREN	= 0x02000000;
			const int WS_CLIPSIBLINGS	= 0x04000000;

			assertStopped();

			// Ensure required properties set
			if ( filename == null )
				throw new ArgumentException( "The Filename property has not been set to a file.\n" );

			// Stop the graph
			if ( mediaControl != null )
				mediaControl.Stop();

			// Create the graph if needed (group should already be created)
			createGraph();

			// Derender the graph if we have a capture or preview stream
			// that we no longer want. We can't derender the capture and 
			// preview streams seperately. 
			// Notice the second case will leave a capture stream intact
			// even if we no longer want it. This allows the user that is
			// not using the preview to Stop() and Start() without
			// rerendering the graph.
			if ( !wantPreviewRendered && isPreviewRendered )
				derenderGraph();
			if ( !wantCaptureRendered && isCaptureRendered )
				if ( wantPreviewRendered )
				{
					derenderGraph();
					graphState = GraphState.Null;
					createGraph();
				}

			// Video Capture
			// ===================================================================================
			if ( wantCaptureRendered && !isCaptureRendered )
			{
                            
				// Render the file writer portion of graph (mux -> file)
				Guid mediaSubType = MediaSubType.Avi;
				hr = captureGraphBuilder.SetOutputFileName( ref mediaSubType, Filename, out muxFilter, out fileWriterFilter );
				//if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

				if ( VideoDevice != null )
				{
					// Try interleaved first, because if the device supports it,
					// it's the only way to get audio as well as video
					cat = PinCategory.Capture;
					med = MediaType.Interleaved;
					hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, videoCompressorFilter, muxFilter); 
					if( hr < 0 ) 
					{
						med = MediaType.Video;
						hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, videoCompressorFilter, muxFilter);
						//if ( hr == -2147220969 ) throw new DeviceInUseException( "Video device", hr );
						//if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );
					}
				}
				// Render audio (audio -> mux)
				if ( AudioDevice != null )
				{
					cat = PinCategory.Capture;
					med = MediaType.Audio;
					hr = captureGraphBuilder.RenderStream( ref cat, ref med, audioDeviceFilter, audioCompressorFilter, muxFilter );
					if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );
				}
				isCaptureRendered = true;
				didSomething = true;
			}


			// Render preview stream and launch the baseGrabFlt to capture frames
			// ===================================================================================
			if ( wantPreviewRendered && renderStream && !isPreviewRendered )
			{
				// Render preview (video.PinPreview -> baseGrabFlt -> renderer)
				// At this point intelligent connect is used, because my webcams don't have a preview pin and
				// a capture pin, so Smart Tee filter will be used. I have tested it using GraphEdit.
				// I can type hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, null, baseGrabFlt); 
				// because baseGrabFlt is a transform filter, like videoCompressorFilter.
				
				cat = PinCategory.Preview;
				med = MediaType.Video;
				hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, baseGrabFlt, null ); 
				//if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

				// Get the IVideoWindow interface
				videoWindow = (IVideoWindow) graphBuilder;

				// Set the video window to be a child of the main window
				hr = videoWindow.put_Owner( previewWindow.Handle );
				//if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

				// Set video window style
				hr = videoWindow.put_WindowStyle( WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
				//if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

				// Position video window in client rect of owner window
				previewWindow.Resize += new EventHandler( onPreviewWindowResize );
				onPreviewWindowResize( this, null );

				// Make the video window visible, now that it is properly positioned
				hr = videoWindow.put_Visible( DsHlp.OATRUE );
				//if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

				hr = mediaEvt.SetNotifyWindow( this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero );
				//if( hr < 0 )
				//	Marshal.ThrowExceptionForHR( hr );

				isPreviewRendered = true;
				didSomething = true;

				// Begin Configuration of SampGrabber	<<<<<<----------------------------------------------------
                
				AMMediaType media = new AMMediaType();
				hr = sampGrabber.GetConnectedMediaType( media );
				//if( hr < 0 )
				//	Marshal.ThrowExceptionForHR( hr );
				if( (media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero) )
					throw new NotSupportedException( "Unknown Grabber Media Format" ); 

				videoInfoHeader = (VideoInfoHeader) Marshal.PtrToStructure( media.formatPtr, typeof(VideoInfoHeader) );
				Marshal.FreeCoTaskMem( media.formatPtr ); media.formatPtr = IntPtr.Zero;

				hr = sampGrabber.SetBufferSamples( false );
				if( hr == 0 )
					hr = sampGrabber.SetOneShot( false );
				if( hr == 0 )
					hr = sampGrabber.SetCallback( null, 0 );
				//if( hr < 0 )
				//	Marshal.ThrowExceptionForHR( hr );	
				
				// Finish Configuration of SampGrabber	<<<<<<----------------------------------------------------
			}
			
			if ( didSomething )
				graphState = GraphState.Rendered;
		}
Ejemplo n.º 36
0
		/// <summary>
		///  Connects the filters of a previously created graph 
		///  (created by createGraph()). Once rendered the graph
		///  is ready to be used. This method may also destroy
		///  streams if we have streams we no longer want.
		/// </summary>
		protected void renderGraph()
		{
			Guid					cat;
			Guid					med;
			int						hr;
			bool					didSomething = false;
#if DSHOWNET
			const int WS_CHILD			= 0x40000000;	
			const int WS_CLIPCHILDREN	= 0x02000000;
			const int WS_CLIPSIBLINGS	= 0x04000000;
#endif

			assertStopped();

			// Ensure required properties set
			if ( filename == null )
				throw new ArgumentException( "The Filename property has not been set to a file.\n" );

			// Stop the graph
			if ( mediaControl != null )
				mediaControl.Stop();

			// Create the graph if needed (group should already be created)
			createGraph();

			// Derender the graph if we have a capture or preview stream
			// that we no longer want. We can't derender the capture and 
			// preview streams seperately. 
			// Notice the second case will leave a capture stream intact
			// even if we no longer want it. This allows the user that is
			// not using the preview to Stop() and Start() without
			// rerendering the graph.
			if ( !wantPreviewRendered && isPreviewRendered )
				derenderGraph();
			if ( !wantCaptureRendered && isCaptureRendered )
				if ( wantPreviewRendered )
					derenderGraph();


			// Render capture stream (only if necessary)
			if ( wantCaptureRendered && !isCaptureRendered )
			{
				// Render the file writer portion of graph (mux -> file)
				// Record captured audio/video in Avi, Wmv or Wma format
				Guid mediaSubType; // Media sub type
				bool captureAudio = true;
				bool captureVideo = true;
				IBaseFilter videoCompressorfilter = null;

				// Set media sub type and video compressor filter if needed
				if(RecFileMode == RecFileModeType.Avi)
				{
					mediaSubType = MediaSubType.Avi;
					// For Avi file saving a video compressor must be used
					// If one is selected, that one will be used.
					videoCompressorfilter = videoCompressorFilter;
				}
				else
				{
					mediaSubType = MediaSubType.Asf;
				}

				// Intialize the Avi or Asf file writer
#if DSHOWNET
                hr = captureGraphBuilder.SetOutputFileName(ref mediaSubType, Filename, out muxFilter, out fileWriterFilter);
#else
                hr = captureGraphBuilder.SetOutputFileName(mediaSubType, Filename, out muxFilter, out fileWriterFilter);
#endif
				if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

				// For Wma (and Wmv) a suitable profile must be selected. This
				// can be done via a property window, however the muxFilter is
				// just created. if needed, the property windows should show up
				// right now!
				// Another solution is to configure the Asf file writer, the
				// use interface must ensure the proper format has been
				// selected.
				if((RecFileMode == RecFileModeType.Wma)||
					(RecFileMode == RecFileModeType.Wmv))
				{
					if(this.AsfFormat != null)
					{
						this.AsfFormat.UpdateAsfAVFormat(this.muxFilter);
						this.AsfFormat.GetCurrentAsfAVInfo(out captureAudio, out captureVideo);
					}
				}

				// Render video (video -> mux) if needed or possible
				if((VideoDevice != null)&&(captureVideo))
                {
					// Try interleaved first, because if the device supports it,
					// it's the only way to get audio as well as video
					cat = PinCategory.Capture;
					med = MediaType.Interleaved;
#if DSHOWNET
                    hr = captureGraphBuilder.RenderStream(ref cat, ref med, videoDeviceFilter, videoCompressorfilter, muxFilter);
#else
					hr = captureGraphBuilder.RenderStream( DsGuid.FromGuid(cat), DsGuid.FromGuid(med), videoDeviceFilter, videoCompressorFilter, muxFilter ); 
#endif
					if( hr < 0 ) 
					{
						med = MediaType.Video;
#if DSHOWNET
                        hr = captureGraphBuilder.RenderStream(ref cat, ref med, videoDeviceFilter, videoCompressorfilter, muxFilter);
#else
						hr = captureGraphBuilder.RenderStream( DsGuid.FromGuid(cat), DsGuid.FromGuid(med), videoDeviceFilter, videoCompressorFilter, muxFilter ); 
#endif
						if ( hr == -2147220969 ) throw new DeviceInUseException( "Video device", hr );
						if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );
					}
				}

				// Render audio (audio -> mux) if possible
				if((audioDeviceFilter != null)&&(captureAudio))
				{
					// If this Asf file format than please keep in mind that
					// certain Wmv formats do not have an audio stream, so
					// when using this code, please ensure you use a format
					// which supports audio!
					cat = PinCategory.Capture;
					med = MediaType.Audio;
#if DSHOWNET
					hr = captureGraphBuilder.RenderStream( ref cat, ref med, audioDeviceFilter, audioCompressorFilter, muxFilter ); 
#else
					hr = captureGraphBuilder.RenderStream( DsGuid.FromGuid(cat), DsGuid.FromGuid(med), audioDeviceFilter, audioCompressorFilter, muxFilter );
#endif
					if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );
				}
				else
					if( (this.AudioViaPci)&&(captureAudio)&&
					(audioDeviceFilter == null)&&(videoDeviceFilter != null) )
				{
					cat = PinCategory.Capture;
					med = MediaType.Audio;
#if DSHOWNET
					hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, audioCompressorFilter, muxFilter );
#else
                    hr = captureGraphBuilder.RenderStream(cat, med, videoDeviceFilter, audioCompressorFilter, muxFilter);
#endif
					if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );
				}

				isCaptureRendered = true;
				didSomething = true;
			}

			// Render preview stream (only if necessary)
			if ( wantPreviewRendered && !isPreviewRendered )
			{
				// Render preview (video -> renderer)
				this.InitVideoRenderer();
				this.AddDeInterlaceFilter();

				// When capture pin is used, preview works immediately,
				// however this conflicts with file saving.
				// An alternative is to use VMR9
                cat = PinCategory.Preview;
				med = MediaType.Video;
// #if NEWCODE
				if(this.InitSampleGrabber())
				{
					Debug.WriteLine("SampleGrabber added to graph.");

#if DSHOWNET
					hr = captureGraphBuilder.RenderStream(ref cat, ref med, videoDeviceFilter, this.baseGrabFlt, this.videoRendererFilter); 
#else
					hr = captureGraphBuilder.RenderStream(DsGuid.FromGuid(cat), DsGuid.FromGuid(med), videoDeviceFilter, this.baseGrabFlt, this.videoRendererFilter); 
#endif
					if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );
				}
				else
// #endif NEWCODE
				{
#if DSHOWNET
					hr = captureGraphBuilder.RenderStream(ref cat, ref med, videoDeviceFilter, null, this.videoRendererFilter);
#else
					hr = captureGraphBuilder.RenderStream(DsGuid.FromGuid(cat), DsGuid.FromGuid(med), videoDeviceFilter, null, this.videoRendererFilter); 
#endif
					if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );
				}

				// Special option to enable rendering audio via PCI bus
				if((this.AudioViaPci)&&(audioDeviceFilter != null))
				{
					cat = PinCategory.Preview;
					med = MediaType.Audio;
#if DSHOWNET
					hr = captureGraphBuilder.RenderStream( ref cat, ref med, audioDeviceFilter, null, null ); 
#else
                    hr = captureGraphBuilder.RenderStream(DsGuid.FromGuid(cat), DsGuid.FromGuid(med), audioDeviceFilter, null, null);
#endif
					if( hr < 0 )
					{
						Marshal.ThrowExceptionForHR( hr );
					}
				}
				else
					if( (this.AudioViaPci)&&
					(this.audioDeviceFilter == null)&&(this.videoDeviceFilter != null) )
				{
					cat = PinCategory.Preview;
					med = MediaType.Audio;
#if DSHOWNET
					hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, null, null ); 
#else
                    hr = captureGraphBuilder.RenderStream(cat, med, videoDeviceFilter, null, null);
#endif
					if( hr < 0 )
					{
						Marshal.ThrowExceptionForHR( hr );
					}
				}

				// Get the IVideoWindow interface
				videoWindow = (IVideoWindow) graphBuilder;

				// Set the video window to be a child of the main window
				hr = videoWindow.put_Owner( previewWindow.Handle );
				if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

				// Set video window style
#if DSHOWNET
				hr = videoWindow.put_WindowStyle( WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
#else
			    hr = videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings);
#endif
				if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

				// Position video window in client rect of owner window
				previewWindow.Resize += new EventHandler( onPreviewWindowResize );
				onPreviewWindowResize( this, null );

				// Make the video window visible, now that it is properly positioned
#if DSHOWNET
				hr = videoWindow.put_Visible( DsHlp.OATRUE );
#else
				hr = videoWindow.put_Visible( OABool.True );
#endif
				if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

				isPreviewRendered = true;
				didSomething = true;
// #if NEWCODE
				SetMediaSampleGrabber();
// #endif NEWCODE
			}

			if ( didSomething )
				graphState = GraphState.Rendered;
		}
Ejemplo n.º 37
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;
        }
Ejemplo n.º 38
0
        private static void ConfigureVideoWindow(IVideoWindow videoWindow, Control hWin)
        {
            int hr = videoWindow.put_Owner(hWin.Handle);
            if (hr >= 0)
            {
                hr = videoWindow.put_WindowStyle((WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings));
                DsError.ThrowExceptionForHR(hr);

                hr = videoWindow.put_Visible(OABool.True);
                DsError.ThrowExceptionForHR(hr);

                Rectangle rc = hWin.ClientRectangle;
                hr = videoWindow.SetWindowPosition(0, 0, rc.Right, rc.Bottom);
                DsError.ThrowExceptionForHR(hr);
            }
        }
Ejemplo n.º 39
0
        // Configure the video window
        private void ConfigureVideoWindow(IVideoWindow videoWindow, GraphicsDevice hWin)
        {
            int hr;

            // Set the output window
            hr = videoWindow.put_Owner( hWin.Adapter.MonitorHandle ); //CHANGE
            DsError.ThrowExceptionForHR( hr );

            // Set the window style
            hr = videoWindow.put_WindowStyle( (WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings) );
            DsError.ThrowExceptionForHR( hr );

            // Make the window visible
            hr = videoWindow.put_Visible( OABool.True );
            DsError.ThrowExceptionForHR( hr );

            // Position the playing location

            hr = videoWindow.SetWindowPosition( 0, 0, 1920, 600 );
            DsError.ThrowExceptionForHR( hr );
        }
Ejemplo n.º 40
0
		/// <summary>
		///  Connects the filters of a previously created graph 
		///  (created by createGraph()). Once rendered the graph
		///  is ready to be used. This method may also destroy
		///  streams if we have streams we no longer want.
		/// </summary>
		private void renderGraph()
		{
			DsGuid cat;
			DsGuid med;
			int hr;
			bool didSomething = false;

			assertStopped();

			// Ensure required properties set
			if (_filename == null)
				throw new ArgumentException("The Filename property has not been set to a file.\n");

			// Stop the graph
			if (_mediaControl != null)
				_mediaControl.Stop();

			// Create the graph if needed (group should already be created)
			createGraph();

			// Derender the graph if we have a capture or preview stream
			// that we no longer want. We can't derender the capture and 
			// preview streams seperately. 
			// Notice the second case will leave a capture stream intact
			// even if we no longer want it. This allows the user that is
			// not using the preview to Stop() and Start() without
			// rerendering the graph.
			if (!_wantPreviewRendered && _isPreviewRendered)
				derenderGraph();
			if (!_wantCaptureRendered && _isCaptureRendered)
				if (_wantPreviewRendered)
					derenderGraph();


			// Render capture stream (only if necessary)
			if (_wantCaptureRendered && !_isCaptureRendered)
			{
				// Render the file writer portion of graph (mux -> file)
				Guid mediaSubType = MediaSubType.Avi;
				Marshal.ThrowExceptionForHR(_captureGraphBuilder.SetOutputFileName(mediaSubType, Filename, out _muxFilter, out _fileWriterFilter));

				// Render video (video -> mux)
				if (VideoDevice != null)
				{
					// Try interleaved first, because if the device supports it,
					// it's the only way to get audio as well as video
					cat = DsGuid.FromGuid(PinCategory.Capture);
					med = DsGuid.FromGuid(MediaType.Interleaved);
					hr = _captureGraphBuilder.RenderStream(cat, med, _videoDeviceFilter, _videoCompressorFilter, _muxFilter);
					//hr = _captureGraphBuilder.RenderStream(ref cat, ref med, _videoDeviceFilter, _videoCompressorFilter, _muxFilter);
					if (hr < 0)
					{
						med = DsGuid.FromGuid(MediaType.Video);
						hr = _captureGraphBuilder.RenderStream(cat, med, _videoDeviceFilter, _videoCompressorFilter, _muxFilter);
						//hr = _captureGraphBuilder.RenderStream(ref cat, ref med, _videoDeviceFilter, _videoCompressorFilter, _muxFilter);
						if (hr == -2147220969) 
							throw new DeviceInUseException("Video device", hr);
						
						Marshal.ThrowExceptionForHR(hr);
					}
				}

				// Render audio (audio -> mux)
				if (AudioDevice != null)
				{
					cat = DsGuid.FromGuid(PinCategory.Capture);
					med = DsGuid.FromGuid(MediaType.Audio);
					Marshal.ThrowExceptionForHR(_captureGraphBuilder.RenderStream(cat, med, _audioDeviceFilter, _audioCompressorFilter, _muxFilter));
					//Marshal.ThrowExceptionForHR(_captureGraphBuilder.RenderStream(ref cat, ref med, _audioDeviceFilter, _audioCompressorFilter, _muxFilter));
				}

				_isCaptureRendered = true;
				didSomething = true;
			}

			// Render preview stream (only if necessary)
			if (_wantPreviewRendered && !_isPreviewRendered)
			{
				// Render preview (video -> renderer)
				cat = DsGuid.FromGuid(PinCategory.Preview);
				med = DsGuid.FromGuid(MediaType.Video);
				Marshal.ThrowExceptionForHR(_captureGraphBuilder.RenderStream(cat,  med, _videoDeviceFilter, null, null));
//				Marshal.ThrowExceptionForHR(_captureGraphBuilder.RenderStream(ref cat, ref med, _videoDeviceFilter, null, null));

				// Get the IVideoWindow interface
				_videoWindow = (IVideoWindow)_graphBuilder;
				
				// Set the video window to be a child of the main window
				Marshal.ThrowExceptionForHR(_videoWindow.put_Owner(_previewWindow.Handle));

				// Set video window style
				Marshal.ThrowExceptionForHR(_videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings));
				//Marshal.ThrowExceptionForHR(_videoWindow.put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS));

				// Position video window in client rect of owner window
				_previewWindow.Resize += new EventHandler(onPreviewWindowResize);
				onPreviewWindowResize(this, null);

				// Make the video window visible, now that it is properly positioned
				Marshal.ThrowExceptionForHR(_videoWindow.put_Visible(OABool.True));

				_isPreviewRendered = true;
				didSomething = true;
			}

			if (didSomething)
				_graphState = GraphState.Rendered;
		}
Ejemplo n.º 41
0
    /// <summary> do cleanup and release DirectShow. </summary>
    protected void CloseInterfaces()
    {
      if (_graphBuilder == null)
      {
        return;
      }
      Log.Debug("BDPlayer: Cleanup DShow graph {0}", GUIGraphicsContext.InVmr9Render);
      try
      {
        BDOSDRenderer.StopRendering();

        if (VMR9Util.g_vmr9 != null)
        {
          VMR9Util.g_vmr9.Vmr9MediaCtrl(_mediaCtrl);
          VMR9Util.g_vmr9.Enable(false);
        }

        #region Cleanup

        if (VideoCodec != null)
        {
          DirectShowUtil.FinalReleaseComObject(VideoCodec);
          VideoCodec = null;
          Log.Info("BDPlayer: Cleanup VideoCodec");
        }

        if (AudioCodec != null)
        {
          DirectShowUtil.FinalReleaseComObject(AudioCodec);
          AudioCodec = null;
          Log.Info("BDPlayer: Cleanup AudioCodec");
        }

        if (_audioRendererFilter != null)
        {
          DirectShowUtil.FinalReleaseComObject(_audioRendererFilter);
          _audioRendererFilter = null;
          Log.Info("BDPlayer: Cleanup AudioRenderer");
        }

        //Test to ReleaseComObject from PostProcessFilter list objects.
        if (PostProcessFilterVideo.Count > 0)
        {
          foreach (var ppFilter in PostProcessFilterVideo)
          {
            if (ppFilter.Value != null)
            {
              DirectShowUtil.RemoveFilter(_graphBuilder, ppFilter.Value as IBaseFilter);
              DirectShowUtil.FinalReleaseComObject(ppFilter.Value);
            }
          }
          PostProcessFilterVideo.Clear();
          Log.Info("BDPlayer: Cleanup PostProcessVideo");
        }

        //Test to ReleaseComObject from PostProcessFilter list objects.
        if (PostProcessFilterAudio.Count > 0)
        {
          foreach (var ppFilter in PostProcessFilterAudio)
          {
            if (ppFilter.Value != null)
            {
              DirectShowUtil.RemoveFilter(_graphBuilder, ppFilter.Value as IBaseFilter);
              DirectShowUtil.FinalReleaseComObject(ppFilter.Value);
            }
          }
          PostProcessFilterAudio.Clear();
          Log.Info("BDPlayer: Cleanup PostProcessAudio");
        }

        if (_interfaceBDReader != null)
        {
          DirectShowUtil.FinalReleaseComObject(_interfaceBDReader);
          _interfaceBDReader = null;
        }

        if (VMR9Util.g_vmr9 != null && VMR9Util.g_vmr9._vmr9Filter != null)
        {
          //MadvrInterface.EnableExclusiveMode(false, VMR9Util.g_vmr9._vmr9Filter);
          //DirectShowUtil.DisconnectAllPins(_graphBuilder, VMR9Util.g_vmr9._vmr9Filter);
          Log.Info("BDPlayer: Cleanup VMR9");
        }

        #endregion

        _videoWin = _graphBuilder as IVideoWindow;
        if (_videoWin != null && GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR)
        {
          _videoWin.put_Owner(IntPtr.Zero);
          _videoWin.put_Visible(OABool.False);
        }

        if (_mediaEvt != null)
        {
          _mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
          _mediaEvt = null;
        }

        if (_graphBuilder != null)
        {
          DirectShowUtil.RemoveFilters(_graphBuilder);
          if (_rotEntry != null)
          {
            _rotEntry.SafeDispose();
            _rotEntry = null;
          }
          DirectShowUtil.FinalReleaseComObject(_graphBuilder);
          _graphBuilder = null;
        }

        if (_videoWin != null)
        {
          DirectShowUtil.FinalReleaseComObject(_videoWin);
        }
        if (_basicVideo != null)
        {
          DirectShowUtil.FinalReleaseComObject(_basicVideo);
        }
        _mediaCtrl = null;
        _mediaSeeking = null;
        _videoWin = null;
        _basicAudio = null;
        _basicVideo = null;
        _ireader = null;

        if (VMR9Util.g_vmr9 != null)
        {
          VMR9Util.g_vmr9.SafeDispose();
          VMR9Util.g_vmr9 = null;
        }

        _state = PlayState.Init;
      }
      catch (Exception ex)
      {
        if (VMR9Util.g_vmr9 != null)
        {
          VMR9Util.g_vmr9.RestoreGuiForMadVr();
        }
        Log.Error("BDPlayer: Exception while cleaning DShow graph - {0} {1}", ex.Message, ex.StackTrace);
      }
      //switch back to directx windowed mode
      ExclusiveMode(false);
    }
Ejemplo n.º 42
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;
                }
            }
        }
        public bool Play(string fileName, Control parent, out string ErrorOrSplitter)
        {
            ErrorOrSplitter = "";
            int hr;
            _parentControl = parent;

            _graphBuilder = (IFilterGraph2)new FilterGraph();
            _rotEntry = new DsROTEntry(_graphBuilder);

            // add the video renderer (evr does not seem to work here)
            IBaseFilter vmr9Renderer = DirectShowUtil.AddFilterToGraph(_graphBuilder, "Video Mixing Renderer 9");
            ((IVMRAspectRatioControl9)vmr9Renderer).SetAspectRatioMode(VMRAspectRatioMode.LetterBox);
            DirectShowUtil.ReleaseComObject(vmr9Renderer, 2000);

            // add the audio renderer
            IBaseFilter audioRenderer = DirectShowUtil.AddAudioRendererToGraph(_graphBuilder, MPSettings.Instance.GetValueAsString("movieplayer", "audiorenderer", "Default DirectSound Device"), false);
            DirectShowUtil.ReleaseComObject(audioRenderer, 2000);

            // add the source filter
            string sourceFilterName = OnlineVideos.MediaPortal1.Player.OnlineVideosPlayer.GetSourceFilterName(fileName);
			if (string.IsNullOrEmpty(sourceFilterName)) return false;
            IBaseFilter sourceFilter = null;
            try
            {
                sourceFilter = DirectShowUtil.AddFilterToGraph(_graphBuilder, sourceFilterName);
            }
            catch (Exception ex)
            {
                ErrorOrSplitter = ex.Message;
                return false;
            }

            hr = ((IFileSourceFilter)sourceFilter).Load(fileName, null);

            if (hr != 0)
            {
                ErrorOrSplitter = DirectShowLib.DsError.GetErrorText(hr);
                DirectShowUtil.ReleaseComObject(sourceFilter, 2000);
                return false;
            }

            // wait for our filter to buffer before rendering the pins
            OnlineVideos.MPUrlSourceFilter.IFilterState filterState = sourceFilter as OnlineVideos.MPUrlSourceFilter.IFilterState;

            if (filterState != null)
            {
                bool ready = false;

                while ((!ready) && (hr == 0))
                {
                    hr = filterState.IsFilterReadyToConnectPins(out ready);

                    System.Threading.Thread.Sleep(25);
                }
            }

            if (hr != 0)
            {
                ErrorOrSplitter = DirectShowLib.DsError.GetErrorText(hr);
                DirectShowUtil.ReleaseComObject(sourceFilter, 2000);
                return false;
            }

            OnlineVideos.MediaPortal1.Player.OnlineVideosPlayer.AddPreferredFilters(_graphBuilder, sourceFilter);

            // try to connect the filters
            int numConnected = 0;
            IEnumPins pinEnum;
            hr = sourceFilter.EnumPins(out pinEnum);
            if ((hr == 0) && (pinEnum != null))
            {
                pinEnum.Reset();
                IPin[] pins = new IPin[1];
                int iFetched;
                int iPinNo = 0;
                do
                {
                    iPinNo++;
                    hr = pinEnum.Next(1, pins, out iFetched);
                    if (hr == 0)
                    {
                        if (iFetched == 1 && pins[0] != null)
                        {
                            PinDirection pinDir;
                            pins[0].QueryDirection(out pinDir);
                            if (pinDir == PinDirection.Output)
                            {
                                hr = _graphBuilder.Render(pins[0]);
								if (hr == 0)
								{
									numConnected++;
									IPin connectedPin;
									if (pins[0].ConnectedTo(out connectedPin) == 0 && connectedPin != null)
									{
										PinInfo connectedPinInfo;
										connectedPin.QueryPinInfo(out connectedPinInfo);
										FilterInfo connectedFilterInfo;
										connectedPinInfo.filter.QueryFilterInfo(out connectedFilterInfo);
										DirectShowUtil.ReleaseComObject(connectedPin, 2000);
										IBaseFilter connectedFilter;
										if (connectedFilterInfo.pGraph.FindFilterByName(connectedFilterInfo.achName, out connectedFilter) == 0 && connectedFilter != null)
										{
											var codecInfo = GetCodecInfo(connectedFilter, connectedFilterInfo.achName);
											if (codecInfo != null)
											{
												if (string.IsNullOrEmpty(ErrorOrSplitter)) ErrorOrSplitter = codecInfo.ToString();
												else ErrorOrSplitter += ", " + codecInfo.ToString();
											}
											DirectShowUtil.ReleaseComObject(connectedFilter);
										}
									}
								}
                            }
                            DirectShowUtil.ReleaseComObject(pins[0], 2000);
                        }
                    }
                } while (iFetched == 1);
            }
            DirectShowUtil.ReleaseComObject(pinEnum, 2000);

            if (numConnected > 0)
            {
                _videoWin = _graphBuilder as IVideoWindow;
                if (_videoWin != null)
                {
                    _videoWin.put_Owner(_parentControl.Handle);
                    _videoWin.put_WindowStyle((WindowStyle)((int)WindowStyle.Child + (int)WindowStyle.ClipSiblings + (int)WindowStyle.ClipChildren));
                    _videoWin.SetWindowPosition(_parentControl.ClientRectangle.X, _parentControl.ClientRectangle.Y, _parentControl.ClientRectangle.Width, _parentControl.ClientRectangle.Height);
                    _videoWin.put_Visible(OABool.True);
                }

                _mediaCtrl = (IMediaControl)_graphBuilder;
                hr = _mediaCtrl.Run();

                mediaEvents = (IMediaEventEx)_graphBuilder;
                // Have the graph signal event via window callbacks for performance
                mediaEvents.SetNotifyWindow(_parentControl.FindForm().Handle, WMGraphNotify, IntPtr.Zero);

                _parentControl.SizeChanged += _parentControl_SizeChanged;
                return true;
            }
            else
            {
                ErrorOrSplitter = string.Format("Could not render output pins of {0}", sourceFilterName);
                DirectShowUtil.ReleaseComObject(sourceFilter, 2000);
                Stop();
                return false;
            }
        }
Ejemplo n.º 44
0
        /// <summary>
        ///  Connects the filters of a previously created graph 
        ///  (created by createGraph()). Once rendered the graph
        ///  is ready to be used. This method may also destroy
        ///  streams if we have streams we no longer want.
        /// </summary>
        protected void renderGraph()
        {
            Guid					cat;
            Guid					med;
            int						hr;
            bool					didSomething = false;
            const int WS_CHILD			= 0x40000000;
            const int WS_CLIPCHILDREN	= 0x02000000;
            const int WS_CLIPSIBLINGS	= 0x04000000;

            assertStopped();

            // Ensure required properties set
            if ( filename == null )
                throw new ArgumentException( "The Filename property has not been set to a file.\n" );

            // Stop the graph
            if ( mediaControl != null )
                mediaControl.Stop();

            // Create the graph if needed (group should already be created)
            createGraph();

            // Derender the graph if we have a capture or preview stream
            // that we no longer want. We can't derender the capture and
            // preview streams seperately.
            // Notice the second case will leave a capture stream intact
            // even if we no longer want it. This allows the user that is
            // not using the preview to Stop() and Start() without
            // rerendering the graph.
            if ( !wantPreviewRendered && isPreviewRendered )
                derenderGraph();
            if ( !wantCaptureRendered && isCaptureRendered )
                if ( wantPreviewRendered )
                    derenderGraph();

            // Render capture stream (only if necessary)
            if ( wantCaptureRendered && !isCaptureRendered )
            {
                // Render the file writer portion of graph (mux -> file)
                Guid mediaSubType = MediaSubType.Avi;
                hr = captureGraphBuilder.SetOutputFileName( ref mediaSubType, Filename, out muxFilter, out fileWriterFilter );
                if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

                // Render video (video -> mux)
                if ( VideoDevice != null )
                {
                    // Try interleaved first, because if the device supports it,
                    // it's the only way to get audio as well as video
                    cat = PinCategory.Capture;
                    med = MediaType.Interleaved;
                    hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, videoCompressorFilter, muxFilter );
                    if( hr < 0 )
                    {
                        med = MediaType.Video;
                        hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, videoCompressorFilter, muxFilter );
                        if ( hr == -2147220969 ) throw new DeviceInUseException( "Video device", hr );
                        if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );
                    }
                }

                // Render audio (audio -> mux)
                if ( AudioDevice != null )
                {
                    cat = PinCategory.Capture;
                    med = MediaType.Audio;
                    hr = captureGraphBuilder.RenderStream( ref cat, ref med, audioDeviceFilter, audioCompressorFilter, muxFilter );
                    if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );
                }

                isCaptureRendered = true;
                didSomething = true;
            }

            // Render preview stream (only if necessary)
            if ( wantPreviewRendered && !isPreviewRendered )
            {
                // Render preview (video -> renderer)
                cat = PinCategory.Preview;
                med = MediaType.Video;
                hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, null, null );
                if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

                // Get the IVideoWindow interface
                videoWindow = (IVideoWindow) graphBuilder;

                // Set the video window to be a child of the main window
                hr = videoWindow.put_Owner( previewWindow.Handle );
                if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

                // Set video window style
                hr = videoWindow.put_WindowStyle( WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
                if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

                // Position video window in client rect of owner window
                previewWindow.Resize += new EventHandler( onPreviewWindowResize );
                onPreviewWindowResize( this, null );

                // Make the video window visible, now that it is properly positioned
                hr = videoWindow.put_Visible( DsHlp.OATRUE );
                if( hr < 0 ) Marshal.ThrowExceptionForHR( hr );

                isPreviewRendered = true;
                didSomething = true;
            }

            if ( didSomething )
                graphState = GraphState.Rendered;
        }
Ejemplo n.º 45
0
    /// <summary>
    /// Configure the video window
    /// </summary>
    /// <param name="videoWindow">Interface of the video renderer</param>
    /// <param name="previewControl">Preview Control to draw into</param>
    private void ConfigureVideoWindow(IVideoWindow videoWindow, Control previewControl)
    {
      int hr;

      if (previewControl == null)
      {
        return;
      }

      // Set the output window
      hr = videoWindow.put_Owner(ThreadSafe.GetHandle(previewControl));
      if (hr >= 0) // If there is video
      {
        // Set the window style
        hr = videoWindow.put_WindowStyle((WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings));
        DsError.ThrowExceptionForHR(hr);

        // Make the window visible
        hr = videoWindow.put_Visible(OABool.True);
        DsError.ThrowExceptionForHR(hr);

        // Position the playing location
        Rectangle rc = ThreadSafe.GetClientRectangle(previewControl);
        hr = videoWindow.SetWindowPosition(0, 0, rc.Right, rc.Bottom);
        DsError.ThrowExceptionForHR(hr);
      }
    }
Ejemplo n.º 46
0
    /// <summary> do cleanup and release DirectShow. </summary>
    protected void CloseInterfaces()
    {
      if (_graphBuilder == null)
      {
        return;
      }
      int hr;
      Log.Debug("BDPlayer: Cleanup DShow graph {0}", GUIGraphicsContext.InVmr9Render);
      try
      {
        BDOSDRenderer.Release();
        
        if (_mediaCtrl != null)
        {
          int counter = 0;
          FilterState state;
          hr = _mediaCtrl.Stop();
          hr = _mediaCtrl.GetState(10, out state);
          while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render)
          {
            Thread.Sleep(100);
            hr = _mediaCtrl.GetState(10, out state);
            counter++;
            if (counter >= 30)
            {
              if (state != FilterState.Stopped)
                Log.Error("BDPlayer: graph still running");
              if (GUIGraphicsContext.InVmr9Render)
                Log.Error("BDPlayer: in renderer");
              break;
            }
          }
          _mediaCtrl = null;
        }

        if (_vmr9 != null)
        {
          _vmr9.Enable(false);
        }

        if (_mediaEvt != null)
        {
          hr = _mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
          _mediaEvt = null;
        }

        _videoWin = _graphBuilder as IVideoWindow;
        if (_videoWin != null)
        {
          hr = _videoWin.put_Visible(OABool.False);
          hr = _videoWin.put_Owner(IntPtr.Zero);
          _videoWin = null;
        }

        _mediaSeeking = null;
        _basicAudio = null;
        _basicVideo = null;
        _ireader = null;

        #region Cleanup Sebastiii

        if (VideoCodec != null)
        {
          DirectShowUtil.ReleaseComObject(VideoCodec, 5000);
          VideoCodec = null;
          Log.Info("BDPlayer: Cleanup VideoCodec");
        }

        if (AudioCodec != null)
        {
          DirectShowUtil.ReleaseComObject(AudioCodec, 5000);
          AudioCodec = null;
          Log.Info("BDPlayer: Cleanup AudioCodec");
        }

        if (_audioRendererFilter != null)
        {
          while (DirectShowUtil.ReleaseComObject(_audioRendererFilter) > 0) ;
          _audioRendererFilter = null;
          Log.Info("BDPlayer: Cleanup AudioRenderer");
        }

        //Test to ReleaseComObject from PostProcessFilter list objects.
        if (PostProcessFilterVideo.Count > 0)
        {
          foreach (var ppFilter in PostProcessFilterVideo)
          {
            if (ppFilter.Value != null) DirectShowUtil.ReleaseComObject(ppFilter.Value, 5000);
          }
          PostProcessFilterVideo.Clear();
          Log.Info("BDPlayer: Cleanup PostProcessVideo");
        }

        //Test to ReleaseComObject from PostProcessFilter list objects.
        if (PostProcessFilterAudio.Count > 0)
        {
          foreach (var ppFilter in PostProcessFilterAudio)
          {
            if (ppFilter.Value != null) DirectShowUtil.ReleaseComObject(ppFilter.Value, 5000);
          }
          PostProcessFilterAudio.Clear();
          Log.Info("BDPlayer: Cleanup PostProcessAudio");
        }

        #endregion

        if (_interfaceBDReader != null)
        {
          DirectShowUtil.ReleaseComObject(_interfaceBDReader, 5000);
          _interfaceBDReader = null;
        }

        if (_graphBuilder != null)
        {
          DirectShowUtil.RemoveFilters(_graphBuilder);
          if (_rotEntry != null)
          {
            _rotEntry.SafeDispose();
            _rotEntry = null;
          }
          while ((hr = DirectShowUtil.ReleaseComObject(_graphBuilder)) > 0) ;
          _graphBuilder = null;
        }

        if (_dvbSubRenderer != null)
        {
          _dvbSubRenderer.SetPlayer(null);
          _dvbSubRenderer = null;
        }

        if (_vmr9 != null)
        {
          _vmr9.SafeDispose();
          _vmr9 = null;
        }

        GUIGraphicsContext.form.Invalidate(true);
        _state = PlayState.Init;
      }
      catch (Exception ex)
      {
        Log.Error("BDPlayer: Exception while cleaning DShow graph - {0} {1}", ex.Message, ex.StackTrace);
      }
      //switch back to directx windowed mode
      ExclusiveMode(false);
    }
Ejemplo n.º 47
0
    private void Cleanup()
    {
      if (graphBuilder == null)
      {
        return;
      }
      int hr;
      Log.Info("RTSPPlayer:cleanup DShow graph");
      try
      {
        if (_mediaCtrl != null)
        {
          int counter = 0;
          FilterState state;
          hr = _mediaCtrl.Stop();
          hr = _mediaCtrl.GetState(10, out state);
          while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render)
          {
            Thread.Sleep(100);
            hr = _mediaCtrl.GetState(10, out state);
            counter++;
            if (counter >= 30)
            {
              if (state != FilterState.Stopped)
                Log.Error("RTSPPlayer: graph still running");
              if (GUIGraphicsContext.InVmr9Render)
                Log.Error("RTSPPlayer: in renderer");
              break;
            }
          }
          _mediaCtrl = null;
        }

        if (Vmr9 != null)
        {
          Vmr9.Enable(false);
        }

        if (mediaEvt != null)
        {
          hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
          mediaEvt = null;
        }

        videoWin = graphBuilder as IVideoWindow;
        if (videoWin != null)
        {
          hr = videoWin.put_Visible(OABool.False);
          hr = videoWin.put_Owner(IntPtr.Zero);
          videoWin = null;
        }

        _mediaSeeking = null;
        mediaPos = null;
        basicAudio = null;
        basicVideo = null;
        videoWin = null;
        SubEngine.GetInstance().FreeSubtitles();

        if (graphBuilder != null)
        {
          DirectShowUtil.RemoveFilters(graphBuilder);
          if (_rotEntry != null)
          {
            _rotEntry.SafeDispose();
            _rotEntry = null;
          }
          DirectShowUtil.ReleaseComObject(graphBuilder);
          graphBuilder = null;
        }

        if (Vmr9 != null)
        {
          Vmr9.SafeDispose();
          Vmr9 = null;
        }

        GUIGraphicsContext.form.Invalidate(true);
        _state = PlayState.Init;

        if (_mpegDemux != null)
        {
          Log.Info("cleanup mpegdemux");
          while ((hr = DirectShowUtil.ReleaseComObject(_mpegDemux)) > 0)
          {
            ;
          }
          _mpegDemux = null;
        }
        if (_rtspSource != null)
        {
          Log.Info("cleanup _rtspSource");
          while ((hr = DirectShowUtil.ReleaseComObject(_rtspSource)) > 0)
          {
            ;
          }
          _rtspSource = null;
        }
        if (_subtitleFilter != null)
        {
          while ((hr = DirectShowUtil.ReleaseComObject(_subtitleFilter)) > 0)
          {
            ;
          }
          _subtitleFilter = null;
          if (this.dvbSubRenderer != null)
          {
            this.dvbSubRenderer.SetPlayer(null);
          }
          this.dvbSubRenderer = null;
        }


        if (vobSub != null)
        {
          Log.Info("cleanup vobSub");
          while ((hr = DirectShowUtil.ReleaseComObject(vobSub)) > 0)
          {
            ;
          }
          vobSub = null;
        }
      }
      catch (Exception ex)
      {
        Log.Error("RTSPPlayer: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace);
      }

      //switch back to directx windowed mode
      Log.Info("RTSPPlayer: Disabling DX9 exclusive mode");
      GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null);
      GUIWindowManager.SendMessage(msg);
    }
Ejemplo n.º 48
0
    public bool Play(string fileName, Form form)
    {
      _form = form;
      Log.WriteFile("play:{0}", fileName);
      _graphBuilder = (IFilterGraph2)new FilterGraph();
      _rotEntry = new DsROTEntry(_graphBuilder);

      TsReader reader = new TsReader();
      _tsReader = (IBaseFilter)reader;
      Log.Info("TSReaderPlayer:add TsReader to graph");
      _graphBuilder.AddFilter(_tsReader, "TsReader");

      #region load file in TsReader

      Log.WriteFile("load file in Ts");
      IFileSourceFilter interfaceFile = (IFileSourceFilter)_tsReader;
      if (interfaceFile == null)
      {
        Log.WriteFile("TSReaderPlayer:Failed to get IFileSourceFilter");
        return false;
      }
      int hr = interfaceFile.Load(fileName, null);

      if (hr != 0)
      {
        Log.WriteFile("TSReaderPlayer:Failed to load file");
        return false;
      }

      #endregion

      #region render pin

      Log.Info("TSReaderPlayer:render TsReader outputs");
      IEnumPins enumPins;
      _tsReader.EnumPins(out enumPins);
      IPin[] pins = new IPin[2];
      int fetched;
      while (enumPins.Next(1, pins, out fetched) == 0)
      {
        if (fetched != 1) break;
        PinDirection direction;
        pins[0].QueryDirection(out direction);
        if (direction == PinDirection.Input)
        {
          Release.ComObject(pins[0]);
          continue;
        }
        _graphBuilder.Render(pins[0]);
        Release.ComObject(pins[0]);
      }
      Release.ComObject(enumPins);

      #endregion

      _videoWin = _graphBuilder as IVideoWindow;
      if (_videoWin != null)
      {
        _videoWin.put_Visible(OABool.True);
        _videoWin.put_Owner(form.Handle);
        _videoWin.put_WindowStyle(
          (WindowStyle)((int)WindowStyle.Child + (int)WindowStyle.ClipSiblings + (int)WindowStyle.ClipChildren));
        _videoWin.put_MessageDrain(form.Handle);

        _videoWin.SetWindowPosition(form.ClientRectangle.X, form.ClientRectangle.Y, form.ClientRectangle.Width,
                                    form.ClientRectangle.Height);
      }

      Log.WriteFile("run graph");
      _mediaCtrl = (IMediaControl)_graphBuilder;
      hr = _mediaCtrl.Run();
      Log.WriteFile("TSReaderPlayer:running:{0:X}", hr);

      return true;
    }
Ejemplo n.º 49
0
        private void ConfigVideo(IVideoWindow ivw, Control hControl)
        {
            int hr;

            hr = ivw.put_Owner(hControl.Handle);
            DsError.ThrowExceptionForHR(hr);

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

            // Yes, make it visible
            hr = ivw.put_Visible( OABool.True );
            DsError.ThrowExceptionForHR( hr );

            // Move to upper left corner
            Rectangle rc = hControl.ClientRectangle;
            hr = ivw.SetWindowPosition( 0, 0, rc.Right, rc.Bottom );
            DsError.ThrowExceptionForHR( hr );
        }