Пример #1
2
        private void BuildGraph(string fileName)
        {
            int hr = 0;

             try
             {
                 graphBuilder = (IFilterGraph2)new FilterGraph();
                 mediaControl = (IMediaControl)graphBuilder;

                 mediaSeeking = (IMediaSeeking)graphBuilder;
                 mediaPosition = (IMediaPosition)graphBuilder;

                 vmr9 = (IBaseFilter)new VideoMixingRenderer9();

                 ConfigureVMR9InWindowlessMode();

                 hr = graphBuilder.AddFilter(vmr9, "Video Mixing Renderer 9");
                 DsError.ThrowExceptionForHR(hr);

                 hr = graphBuilder.RenderFile(fileName, null);
                 DsError.ThrowExceptionForHR(hr);
             }
             catch (Exception e)
             {
                 CloseInterfaces();
                 MessageBox.Show("An error occured during the graph building : \r\n\r\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
        }
Пример #2
0
        /// <summary>
        /// This constructor internally build a DirectShow graph using the given file name parameter.
        /// </summary>
        /// <param name="filename">A media file.</param>
        /// <remarks>This constructor use the BlackListManager class to bane the use of the ffdshow Audio and Video decoders during the Intelligent Connect graph building.</remarks>
        public SimplePlayer(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            throw new ArgumentNullException("filename");

              if (!File.Exists(filename))
            throw new FileNotFoundException();

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

            #if DEBUG
              this.rot = new DsROTEntry(this.graphBuilder);
            #endif

              this.blackListManager = new BlackListManager(this.graphBuilder);

              // blacklist the ffdshow Audio Decoder filter
              this.blackListManager.AddBlackListedFilter(new Guid("0F40E1E5-4F79-4988-B1A9-CC98794E6B55"));
              // blacklist the ffdshow Video Decoder filter
              this.blackListManager.AddBlackListedFilter(new Guid("04FE9017-F873-410E-871E-AB91661A4EF7"));

              int hr = this.graphBuilder.RenderFile(filename, null);
              DsError.ThrowExceptionForHR(hr);

              this.mediaControl = (IMediaControl)this.graphBuilder;
              this.mediaEvent = (IMediaEvent)this.graphBuilder;
        }
Пример #3
0
        public PlayerCore(string file)
        {
            graphBuilder = (new FilterGraph()) as IFilterGraph2;
            if (graphBuilder == null) return;
            mediaControl = graphBuilder as IMediaControl;
            mediaSeeking = graphBuilder as IMediaSeeking;
            audioControl = graphBuilder as IBasicAudio;
            if (mediaControl == null || mediaSeeking == null || audioControl == null) return;
            //int hr = mediaControl.RenderFile(file);
            FileInfo info = new FileInfo(file);
            ISupport support = Supports.Instance[info.Extension];
            int hr = -1;
            if (support != null)
                hr = support.RenderGraph(graphBuilder, file);
            else
                hr = mediaControl.RenderFile(file);

            fileName = file;
            if (hr != 0) errorStack.Push(hr);
            if (hr != 0) return;
            mediaSeeking.SetTimeFormat(TimeFormat.MediaTime);
            isValidate = true;
            window = graphBuilder as IVideoWindow;
            if (window != null)
            {
                int width = 0;
                int height = 0;
                window.get_Width(out width);
                window.get_Height(out height);
                nativeSize = new Size(width, height);
            }
        }
Пример #4
0
        // Starts playing a new cinematic
        public void PlayCinematic(string file, int x, int y, int w, int h)
        {
            // Lame bugfix: DirectShow and Fullscreen doesnt like eachother
            if (CVars.Instance.Get("r_fs", "0", CVarFlags.ARCHIVE).Integer == 1)
            {
                if (AlterGameState)
                {
                    playing = true;
                    StopCinematic();
                }
                return;
            }

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

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

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

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

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

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

            EventCode code;
        }
Пример #5
0
 public void CloseInterfaces()
 {
     if (mediaEvent != null)
     {
         hresult = mediaControl.Stop();
         Marshal.ThrowExceptionForHR(hresult);
     }
     mediaControl = null;
     mediaEvent = null;
     graphBuilder = null;
     if (filterGraph != null) Marshal.ReleaseComObject(filterGraph);
     filterGraph = null;
 }
Пример #6
0
        public CaptureForm()
        {
            InitializeComponent();

            graph_builder = (IGraphBuilder)new FilterGraph();
            media_control = (IMediaControl)graph_builder;
            events = (IMediaEventEx)graph_builder;
            grabber = (ISampleGrabber)new SampleGrabber();

            AMMediaType media_type = new AMMediaType();
            media_type.majorType = MediaType.Video;
            media_type.subType = MediaSubType.RGB24;
            grabber.SetMediaType( media_type );
            grabber.SetCallback( this, 1 );

            cbDevices.Items.AddRange( GetDevices( FilterCategory.VideoInputDevice ) );
        }
Пример #7
0
 // Methods
 internal AudioAnimate(string prefix, string localname, string ns, SvgDocument doc)
     : base(prefix, localname, ns, doc)
 {
     this.m_objFilterGraph = null;
     this.m_objBasicAudio = null;
     this.m_objMediaEvent = null;
     this.m_objMediaEventEx = null;
     this.m_objMediaPosition = null;
     this.m_objMediaControl = null;
     this.fillColor = Color.Khaki;
     this.fileName = string.Empty;
     this.m_CurrentStatus = MediaStatus.None;
     this.timer = new Timer();
     this.oldtime = 0f;
     this.timertime = 0f;
     this.timer.Interval = 100;
     this.timer.Tick += new EventHandler(this.TimerTick);
 }
Пример #8
0
        //Метод CleanUp (Зачистка графов)
        public void CleanUp()
        {
            if (mediaControl != null) mediaControl.Stop();
            CurrentStatus = mStatus.Stop;

            if (videoWindow != null)
            {
                videoWindow.put_Visible(0);
                videoWindow.put_Owner(new IntPtr(0));
            }
            if (mediaControl != null)  mediaControl  = null;
            if (mediaPosition != null) mediaPosition = null;
            if (mediaEventEx != null)  mediaEventEx  = null;
            if (mediaEvent != null)    mediaEvent    = null;
            if (videoWindow != null)   videoWindow   = null;
            if (basicAudio != null)    basicAudio    = null;
            if (graphBuilder != null)  graphBuilder  = null;
        }
Пример #9
0
        /// <summary>
        /// Plays the given mediafile in the internal mediaplayer
        /// </summary>
        /// <param name="FilePath">File to play</param>
        public void ShowMedia(string FilePath)
        {
            StopMedia();
            Lbl_CurrentMedia.Text = Path.GetFileName(FilePath);
            m_objFilterGraph = new FilgraphManager();
            m_objFilterGraph.RenderFile(FilePath);

            m_objBasicAudio = m_objFilterGraph as IBasicAudio;

            try
            {
                m_objVideoWindow = m_objFilterGraph as IVideoWindow;
                m_objVideoWindow.Owner = (int)panel2.Handle;
                //m_objVideoWindow.Owner = (int)panel1.Handle;

                m_objVideoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN;
                m_objVideoWindow.SetWindowPosition(panel2.ClientRectangle.Left,
                   panel2.ClientRectangle.Top,
                    panel2.ClientRectangle.Width,
                    panel2.ClientRectangle.Height);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                m_objVideoWindow = null;
            }

            m_objMediaEvent = m_objFilterGraph as IMediaEvent;

            m_objMediaEventEx = m_objFilterGraph as IMediaEventEx;
            m_objMediaEventEx.SetNotifyWindow((int)this.Handle, WM_GRAPHNOTIFY, 0);

            m_objMediaPosition = m_objFilterGraph as IMediaPosition;

            m_objMediaControl = m_objFilterGraph as IMediaControl;

            m_objMediaControl.Run();
            m_CurrentStatus = MediaStatus.Running;
            UpdateMediaButtons();

            //UpdateStatusBar();
            //UpdateToolBar();
        }
        public void SetControls()
        {
            if (selectedDevice == null)
            {
                launcher = null;
                mediaPlayer = null;
                mediaControl = null;
                tvControl = null;
                volumeControl = null;
                toastControl = null;
                textInputControl = null;
                mouseControl = null;
                externalInputControl = null;
                powerControl = null;
                keyControl = null;
                playListControl = null;
                webAppLauncher = null;
            }
            else
            {
                launcher = selectedDevice.GetCapability<ILauncher>();
                mediaPlayer = selectedDevice.GetCapability<IMediaPlayer>();
                mediaControl = selectedDevice.GetCapability<IMediaControl>();
                tvControl = selectedDevice.GetCapability<ITvControl>();
                volumeControl = selectedDevice.GetCapability<IVolumeControl>();
                toastControl = selectedDevice.GetCapability<IToastControl>();
                textInputControl = selectedDevice.GetCapability<ITextInputControl>();
                mouseControl = selectedDevice.GetCapability<IMouseControl>();
                externalInputControl = selectedDevice.GetCapability<IExternalInputControl>();
                powerControl = selectedDevice.GetCapability<IPowerControl>();
                keyControl = selectedDevice.GetCapability<IKeyControl>();
                playListControl = selectedDevice.GetCapability<IPlayListControl>();
                webAppLauncher = selectedDevice.GetCapability<IWebAppLauncher>();
            }

            SetControlsMedia();
            SetWebAppControls();
            SetControlControls();
            SetControlApps();
            SetControlKeys();
            SetControlSystem();
        }
Пример #11
0
        private void cmdOpen_Click(object sender, EventArgs e)
        {
            // Allow the user to choose a file.
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
            
            if (DialogResult.OK == openFileDialog.ShowDialog())
            {
                // Stop the playback for the current movie, if it exists.
                if (mc != null) mc.Stop();
                mc = null;
                videoWindow = null;

                // Load the movie file.
                FilgraphManager graphManager = new FilgraphManager();
                graphManager.RenderFile(openFileDialog.FileName);

                // Attach the view to a picture box on the form.
                try
                {
                    videoWindow = (IVideoWindow)graphManager;
                    videoWindow.Owner = (int)pictureBox1.Handle;
                    videoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN;
                    videoWindow.SetWindowPosition(pictureBox1.ClientRectangle.Left,
                        pictureBox1.ClientRectangle.Top,
                        pictureBox1.ClientRectangle.Width,
                        pictureBox1.ClientRectangle.Height);
                }
                catch
                {
                    // An error can occur if the file does not have a vide
                    // source (for example, an MP3 file.)
                    // You can ignore this error and still allow playback to
                    // continue (without any visualization).
                }

                // Start the playback (asynchronously).
                mc = (IMediaControl)graphManager;
                mc.Run();
            }
        }
Пример #12
0
        /**
         * To clean up the FilterGraph and other Objects
         * */
        public void CleanUp()
        {
            if (m_objMediaControl != null)
                m_objMediaControl.Stop();

            if (m_objMediaEventEx != null)
                m_objMediaEventEx.SetNotifyWindow(0, 0, 0);

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

            if (m_objMediaControl != null) m_objMediaControl = null;
            if (m_objMediaPosition != null) m_objMediaPosition = null;
            if (m_objMediaEventEx != null) m_objMediaEventEx = null;
            if (m_objMediaEvent != null) m_objMediaEvent = null;
            if (m_objVideoWindow != null) m_objVideoWindow = null;
            if (m_objBasicAudio != null) m_objBasicAudio = null;
            if (m_objFilterGraph != null) m_objFilterGraph = null;
        }
Пример #13
0
        // Build the capture graph for grabber and renderer.</summary>
        // (Control to show video in, Filename to play)
        private void SetupGraph(string FileName)
        {
            int hr;

            // Get the graphbuilder object
            m_FilterGraph = new FilterGraph() as IFilterGraph2;

            // Get a ICaptureGraphBuilder2 to help build the graph
            ICaptureGraphBuilder2 icgb2 = new CaptureGraphBuilder2() as ICaptureGraphBuilder2;

            try
            {
                // Link the ICaptureGraphBuilder2 to the IFilterGraph2
                hr = icgb2.SetFiltergraph(m_FilterGraph);
                DsError.ThrowExceptionForHR(hr);

                // Add the filters necessary to render the file.  This function will
                // work with a number of different file types.
                IBaseFilter sourceFilter = null;
                hr = m_FilterGraph.AddSourceFilter(FileName, FileName, out sourceFilter);
                DsError.ThrowExceptionForHR(hr);

                // Get the SampleGrabber interface
                m_sampGrabber = (ISampleGrabber)new SampleGrabber();
                IBaseFilter baseGrabFlt = (IBaseFilter)m_sampGrabber;

                // Configure the Sample Grabber
                ConfigureSampleGrabber(m_sampGrabber);

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

                // Add the null renderer to the graph
                IBaseFilter nullrenderer = new NullRenderer() as IBaseFilter;
                hr = m_FilterGraph.AddFilter(nullrenderer, "Null renderer");
                DsError.ThrowExceptionForHR(hr);

                // Connect the pieces together, use the default renderer
                hr = icgb2.RenderStream(null, null, sourceFilter, baseGrabFlt, nullrenderer);
                DsError.ThrowExceptionForHR(hr);

                // Now that the graph is built, read the dimensions of the bitmaps we'll be getting
                SaveSizeInfo(m_sampGrabber);

                // Grab some other interfaces
                m_mediaEvent = m_FilterGraph as IMediaEvent;
                m_mediaCtrl = m_FilterGraph as IMediaControl;
            }
            finally
            {
                if (icgb2 != null)
                {
                    Marshal.ReleaseComObject(icgb2);
                    icgb2 = null;
                }
            }
            #if DEBUG
            // Double check to make sure we aren't releasing something
            // important.
            GC.Collect();
            GC.WaitForPendingFinalizers();
            #endif
        }
Пример #14
0
        // Shut down capture
        private void CloseInterfaces()
        {
            int hr;

            lock (this)
            {
                if (m_State != GraphState.Exiting)
                {
                    m_State = GraphState.Exiting;

                    // Release the thread (if the thread was started)
                    if (m_mre != null)
                    {
                        m_mre.Set();
                    }
                }

                if (m_mediaCtrl != null)
                {
                    // Stop the graph
                    hr = m_mediaCtrl.Stop();
                    m_mediaCtrl = null;
                }

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

                if (m_FilterGraph != null)
                {
                    Marshal.ReleaseComObject(m_FilterGraph);
                    m_FilterGraph = null;
                }
            }
            GC.Collect();
        }
Пример #15
0
 /// <summary>
 /// Sets the MediaControl interface
 /// </summary>
 private void SetMediaControlInterface(IMediaControl mediaControl)
 {
     m_mediaControl = mediaControl;
 }
Пример #16
0
        // Thread entry point
        public void WorkerThread()
        {
            // grabber
            Grabber grabber = new Grabber(this);

            // objects
            object graphObj   = null;
            object sourceObj  = null;
            object grabberObj = null;

            // interfaces
            IGraphBuilder graph = null;
            //IBaseFilter sourceBase = null;
            IBaseFilter    grabberBase = null;
            ISampleGrabber sg          = null;
            IMediaControl  mc          = null;

            try
            {
                // Get type for filter graph
                Type srvType = Type.GetTypeFromCLSID(Clsid.FilterGraph);
                if (srvType == null)
                {
                    throw new ApplicationException("Failed creating filter graph");
                }

                // create filter graph
                graphObj = Activator.CreateInstance(srvType);
                graph    = (IGraphBuilder)graphObj;

                // ----
                UCOMIBindCtx bindCtx = null;
                UCOMIMoniker moniker = null;
                int          n       = 0;

                // create bind context
                if (Win32.CreateBindCtx(0, out bindCtx) == 0)
                {
                    // convert moniker`s string to a moniker
                    if (Win32.MkParseDisplayName(bindCtx, source, ref n, out moniker) == 0)
                    {
                        // get device base filter
                        Guid filterId = typeof(IBaseFilter).GUID;
                        moniker.BindToObject(null, null, ref filterId, out sourceObj);

                        Marshal.ReleaseComObject(moniker);
                        moniker = null;
                    }
                    Marshal.ReleaseComObject(bindCtx);
                    bindCtx = null;
                }
                // ----

                if (sourceObj == null)
                {
                    throw new ApplicationException("Failed creating device object for moniker");
                }

                sourceBase = (IBaseFilter)sourceObj;

                // Get type for sample grabber
                srvType = Type.GetTypeFromCLSID(Clsid.SampleGrabber);
                if (srvType == null)
                {
                    throw new ApplicationException("Failed creating sample grabber");
                }

                // create sample grabber
                grabberObj  = Activator.CreateInstance(srvType);
                sg          = (ISampleGrabber)grabberObj;
                grabberBase = (IBaseFilter)grabberObj;

                // add source filter to graph
                graph.AddFilter(sourceBase, "source");
                graph.AddFilter(grabberBase, "grabber");

                // set media type
                AMMediaType mt = new AMMediaType();
                mt.majorType = MediaType.Video;
                mt.subType   = MediaSubType.RGB24;
                sg.SetMediaType(mt);

                // connect pins
                if (graph.Connect(DSTools.GetOutPin(sourceBase, 0), DSTools.GetInPin(grabberBase, 0)) < 0)
                {
                    throw new ApplicationException("Failed connecting filters");
                }

                // get media type
                if (sg.GetConnectedMediaType(mt) == 0)
                {
                    // This is where the actual video input info is obtained
                    VideoInfoHeader vih = (VideoInfoHeader)Marshal.PtrToStructure(mt.formatPtr, typeof(VideoInfoHeader));

                    //System.Diagnostics.Debug.WriteLine("width = " + vih.BmiHeader.Width + ", height = " + vih.BmiHeader.Height);

                    grabber.Width  = vih.BmiHeader.Width;
                    grabber.Height = vih.BmiHeader.Height;
                    mt.Dispose();

                    if (VideoInputSizeDetermined != null)
                    {
                        VideoInputSizeDetermined(this, new Size(vih.BmiHeader.Width, vih.BmiHeader.Height));
                    }
                }

                // render
                graph.Render(DSTools.GetOutPin(grabberBase, 0));

                //
                sg.SetBufferSamples(false);
                sg.SetOneShot(false);
                sg.SetCallback(grabber, 1);

                // window
                IVideoWindow win = (IVideoWindow)graphObj;
                win.put_AutoShow(false);
                win = null;


                // get media control
                mc = (IMediaControl)graphObj;

                // run
                mc.Run();

                while (!stopEvent.WaitOne(0, true))
                {
                    Thread.Sleep(100);
                }
                mc.StopWhenReady();
                //mc.Stop();
            }
            // catch any exceptions
            catch (Exception e)
            {
                try
                {
                    if (CMSLogger.CanCreateLogEvent(true, true, false, "CMSLogExceptionEvent"))
                    {
                        CMSLogExceptionEvent exceptionEvent = new CMSLogExceptionEvent();

                        exceptionEvent.SetException(e);
                        CMSLogger.SendLogEvent(exceptionEvent);
                    }
                }
                catch
                {
                }
            }
            // finalization block
            finally
            {
                // release all objects
                mc          = null;
                graph       = null;
                sourceBase  = null;
                grabberBase = null;
                sg          = null;

                if (graphObj != null)
                {
                    Marshal.ReleaseComObject(graphObj);
                    graphObj = null;
                }
                if (sourceObj != null)
                {
                    Marshal.ReleaseComObject(sourceObj);
                    sourceObj = null;
                }
                if (grabberObj != null)
                {
                    Marshal.ReleaseComObject(grabberObj);
                    grabberObj = null;
                }
            }
        }
Пример #17
0
    private void InitGraph(string filename)
    {
      int hr = 0;
      //IntPtr hEvent;

      if (filename == string.Empty)
        return;

      this.filterGraph = new FilterGraph() as IFilterGraph2;

#if DEBUG
      //rot = new DsROTEntry(this.filterGraph);
#endif

      // Have the graph builder construct its the appropriate graph automatically
      hr = this.filterGraph.RenderFile(filename, null);
      DsError.ThrowExceptionForHR(hr);
      
      // QueryInterface for DirectShow interfaces
      this.mediaControl = this.filterGraph as IMediaControl;
      this.mediaSeeking = this.filterGraph as IMediaSeeking;
      //this.mediaEvent = this.graphBuilder as IMediaEvent;

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

      // Complete window initialization
      this.currentPlaybackRate = 1.0;
    }
Пример #18
0
        private void CloseInterfaces()
        {
            int hr = 0;

              try
              {
            lock(this)
            {
              // Relinquish ownership (IMPORTANT!) after hiding video window
              if (!this.isAudioOnly)
              {
            hr = this.videoWindow.put_Visible(OABool.False);
            DsError.ThrowExceptionForHR(hr);
            hr = this.videoWindow.put_Owner(IntPtr.Zero);
            DsError.ThrowExceptionForHR(hr);
              }

              if (this.mediaEventEx != null)
              {
            hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero);
            DsError.ThrowExceptionForHR(hr);
              }

            #if DEBUG
              if (rot != null)
              {
            rot.Dispose();
            rot = null;
              }
            #endif
              // Release and zero DirectShow interfaces
              if (this.mediaEventEx != null)
            this.mediaEventEx = null;
              if (this.mediaSeeking != null)
            this.mediaSeeking = null;
              if (this.mediaPosition != null)
            this.mediaPosition = null;
              if (this.mediaControl != null)
            this.mediaControl = null;
              if (this.basicAudio != null)
            this.basicAudio = null;
              if (this.basicVideo != null)
            this.basicVideo = null;
              if (this.videoWindow != null)
            this.videoWindow = null;
              if (this.frameStep != null)
            this.frameStep = null;
              if (this.graphBuilder != null)
            Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null;

              GC.Collect();
            }
              }
              catch
              {
              }
        }
Пример #19
0
        /// <summary> build the capture graph for grabber. </summary>
        private void SetupGraph(DsDevice dev, AMMediaType media)
        {
            int hr;

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

            // Get the graphbuilder object
            m_FilterGraph = (IFilterGraph2) new FilterGraph();
            m_mediaCtrl = m_FilterGraph as IMediaControl;
            try
            {
                // Get the ICaptureGraphBuilder2
                capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();

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

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

                // Add the video device
                hr = m_FilterGraph.AddSourceFilterForMoniker(dev.Mon, null, "Video input", out capFilter);
                DsError.ThrowExceptionForHR( hr );

                // add video crossbar
                // thanks to Andrew Fernie - this is to get tv tuner cards working
                IAMCrossbar crossbar = null;
                object o;

                hr = capGraph.FindInterface(PinCategory.Capture, MediaType.Video, capFilter, typeof(IAMCrossbar).GUID, out o);
                if (hr >= 0)
                {
                    crossbar = (IAMCrossbar)o;
                    int oPin, iPin;
                    int ovLink, ivLink;
                    ovLink = ivLink = 0;

                    crossbar.get_PinCounts(out oPin, out iPin);
                    int pIdxRel;
                    PhysicalConnectorType tp;
                    for (int i = 0; i < iPin; i++)
                    {
                        crossbar.get_CrossbarPinInfo(true, i, out pIdxRel, out tp);
                        if (tp == PhysicalConnectorType.Video_Composite) ivLink = i;
                    }

                    for (int i = 0; i < oPin; i++)
                    {
                        crossbar.get_CrossbarPinInfo(false, i, out pIdxRel, out tp);
                        if (tp == PhysicalConnectorType.Video_VideoDecoder) ovLink = i;
                    }

                    try
                    {
                        crossbar.Route(ovLink, ivLink);
                        o = null;
                    }

                    catch
                    {
                        throw new Exception("Failed to get IAMCrossbar");
                    }
                }

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

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

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

                SetConfigParms(capGraph, capFilter, media);

                hr = capGraph.RenderStream(PinCategory.Capture, MediaType.Video, capFilter, pAVIDecompressor, baseGrabFlt);
                if (hr < 0)
                {
                    hr = capGraph.RenderStream(PinCategory.Capture, MediaType.Video, capFilter, null, baseGrabFlt);
                }

                DsError.ThrowExceptionForHR( hr );

                SaveSizeInfo(sampGrabber);
            }
            finally
            {
                if (capFilter != null)
                {
                    Marshal.ReleaseComObject(capFilter);
                    capFilter = null;
                }
                if (sampGrabber != null)
                {
                    Marshal.ReleaseComObject(sampGrabber);
                    sampGrabber = null;
                }
                if (capGraph != null)
                {
                    Marshal.ReleaseComObject(capGraph);
                    capGraph = null;
                }
            }
        }
Пример #20
0
 private void InitInterfaces()
 {
     try
     {
         // initialise the graph and get the graph builder and media control from it
         _graph = new FilterGraph();
         _mediaEvent = (IMediaEventEx)_graph;
         _graphBuilder = (IGraphBuilder)_graph;
         _mediaControl = (IMediaControl)_graph;
     }
     catch (Exception ex)
     {
         throw new ApplicationException("Couldn't initialise filter graph: " + ex.Message);
     }
 }
Пример #21
0
        /// <summary>
        /// Closes and releases all used interfaces.
        /// </summary>
        public void CloseInterfaces()
        {
            if (VMRenderer != null)
            {
                Marshal.ReleaseComObject(VMRenderer);
                VMRenderer = null;
                WindowlessCtrl = null;
                MixerBitmap = null;
            }

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

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

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

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

            if (Crossbar != null)
            {
                Marshal.ReleaseComObject(Crossbar);
                Crossbar = null;
            }
        }
Пример #22
0
    private void Cleanup()
    {
      Log.Info("DVR2MPG: cleanup");
      if (_rotEntry != null)
      {
        _rotEntry.SafeDispose();
      }
      _rotEntry = null;

      if (mediaControl != null)
      {
        mediaControl.Stop();
        mediaControl = null;
      }
      mediaSeeking = null;
      mediaEvt = null;
      mediaControl = null;

      if (powerDvdMuxer != null)
        DirectShowUtil.ReleaseComObject(powerDvdMuxer);
      powerDvdMuxer = null;

      if (fileWriterFilter != null)
        DirectShowUtil.ReleaseComObject(fileWriterFilter);
      fileWriterFilter = null;

      if (bufferSource != null)
        DirectShowUtil.ReleaseComObject(bufferSource);
      bufferSource = null;

      DirectShowUtil.RemoveFilters(graphBuilder);

      if (graphBuilder != null)
        DirectShowUtil.ReleaseComObject(graphBuilder);
      graphBuilder = null;
    }
Пример #23
0
        /// <summary> build the capture graph for grabber. </summary>
        private void SetupGraph(DsDevice dev, int iFrameRate, int iWidth, int iHeight)
        {
            int hr;

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

            // Get the graphbuilder object
            m_FilterGraph = (IFilterGraph2) new FilterGraph();
            m_mediaCtrl = m_FilterGraph as IMediaControl;
            try
            {
                // Get the ICaptureGraphBuilder2
                capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();

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

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

                // Add the video device
                hr = m_FilterGraph.AddSourceFilterForMoniker(dev.Mon, null, "Video input", out capFilter);
                DsError.ThrowExceptionForHR( hr );

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

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

                // If any of the default config items are set
                if (iFrameRate + iHeight + iWidth > 0)
                {
                    SetConfigParms(capGraph, capFilter, iFrameRate, iWidth, iHeight);
                }

                hr = capGraph.RenderStream( PinCategory.Capture, MediaType.Video, capFilter, null, baseGrabFlt );
                DsError.ThrowExceptionForHR( hr );

                SaveSizeInfo(sampGrabber);
            }
            finally
            {
                if (capFilter != null)
                {
                    Marshal.ReleaseComObject(capFilter);
                    capFilter = null;
                }
                if (sampGrabber != null)
                {
                    Marshal.ReleaseComObject(sampGrabber);
                    sampGrabber = null;
                }
                if (capGraph != null)
                {
                    Marshal.ReleaseComObject(capGraph);
                    capGraph = null;
                }
            }
        }
Пример #24
0
        protected override void Run()
        {
#if !DEBUG
            WindowsNamedPipe pipe1 = new WindowsNamedPipe("hdpvr.ts", true);
            WindowsNamedPipe pipe2 = new WindowsNamedPipe("hdpvr.ts", true);
#endif

            try
            {

#if !DEBUG
                if (!File.Exists(filterGraphFile))
                    throw new System.Exception("Filter graph file doesn't exist: " + filterGraphFile);
                graphBuilder = (IGraphBuilder)new FilterGraph();
                FilterGraphTools.LoadGraphFile(graphBuilder, filterGraphFile);

                SetSaveFile(SAVEFILEPIPE);

                setFiltProp(graphBuilder, "Hauppauge HD PVR Encoder", HDPVRAvgBitrate, 0, 3000000);
                setFiltProp(graphBuilder, "Hauppauge HD PVR Encoder", HDPVRPeakBitrate, 0, 3000000);
                setFiltProp(graphBuilder, "Hauppauge HD PVR Encoder", HDPVRBitrateMode, 0, 0);

                mediaControl = (IMediaControl)this.graphBuilder;
                mediaControl.Run();
#endif
            }
            catch (Exception e)
            {
                Log.WriteLine(e.ToString());
                return;
            }

#if !DEBUG
            new Thread(new ThreadStart(delegate
            {
                byte[] tmp = new byte[188];
                pipe1._connected.WaitOne();
                while (true)
                {
                    int readcount = pipe1.Read(tmp);
                    Log.WriteLine(readcount.ToString());
                    if (readcount > 0)
                    {
                        Log.WriteLine("pipe1 read " + readcount + " bytes, this is not normal");
                    }
                    else if (readcount == -1)
                    {
                        Log.WriteLine("pipe1 disconnected, do not worry, this is normal");
                        pipe1.Close();
                        break;
                    }
                }
            })).Start();
#endif
            byte[] readbuffer = new byte[188 * 20 * 1024];
            int loopcount = 0;
            DateTime noneReceiverFrom = DateTime.Now;
            try
            {

                while (true)
                {
#if !DEBUG
                    int readcount = pipe2.Read(readbuffer);

                    if (readcount == -1)
                    {
                        if (loopcount < 10)
                        {
                            Thread.Sleep(1000);
                            loopcount++;
                            continue;
                        }
                        Log.WriteLine("pipe2 disconnected");
                        pipe2.Close();
                        return;
                    }
                    Thread.Sleep(1000);
#else
                                FileStream fs = new FileStream("c:\\0.ts", FileMode.Open, FileAccess.Read);
                                int readcount = fs.Read(readbuffer, 0, readbuffer.Length);
#endif
                    loopcount = 0;
                    lock (this.receiveStreams)
                    {
                        if (receiveStreams.Count > 0)
                            noneReceiverFrom = DateTime.Now;
                        else if ((DateTime.Now - noneReceiverFrom).TotalSeconds > 60 && this.working)
                        { 
                            //关闭
                            new Thread(new ThreadStart(delegate {
                                this.Stop();
                            })).Start();
                            return;
                        }
                        foreach (Stream s in receiveStreams)
                        {
                            s.Write(readbuffer, 0, readcount);
                            Log.WriteLine("写入" + readcount + "字节");
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
                return;
            }
            catch (Exception e)
            {
                Log.WriteLine(e.ToString());
                return;
            }
        }
Пример #25
0
    public bool Transcode(TranscodeInfo info, MediaPortal.Core.Transcoding.VideoFormat format,
                          MediaPortal.Core.Transcoding.Quality quality, Standard standard)
    {
      if (!Supports(format)) return false;
      string ext = System.IO.Path.GetExtension(info.file);
      if (ext.ToLower() != ".dvr-ms" && ext.ToLower() != ".sbe") return false;

      //Type comtype = null;
      //object comobj = null;
      try
      {
        Log.Info("DVR2MPG: create graph");
        graphBuilder = (IGraphBuilder)new FilterGraph();

        _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder);

        Log.Info("DVR2MPG: add streambuffersource");
        bufferSource = (IStreamBufferSource)new StreamBufferSource();


        IBaseFilter filter = (IBaseFilter)bufferSource;
        graphBuilder.AddFilter(filter, "SBE SOURCE");

        Log.Info("DVR2MPG: load file:{0}", info.file);
        IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource;
        int hr = fileSource.Load(info.file, null);


        Log.Info("DVR2MPG: Add Cyberlink MPEG2 multiplexer to graph");
        string monikerPowerDvdMuxer =
          @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{7F2BBEAF-E11C-4D39-90E8-938FB5A86045}";
        powerDvdMuxer = Marshal.BindToMoniker(monikerPowerDvdMuxer) as IBaseFilter;
        if (powerDvdMuxer == null)
        {
          Log.Warn("DVR2MPG: FAILED:Unable to create Cyberlink MPEG Muxer (PowerDVD)");
          Cleanup();
          return false;
        }

        hr = graphBuilder.AddFilter(powerDvdMuxer, "PDR MPEG Muxer");
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED:Add Cyberlink MPEG Muxer to filtergraph :0x{0:X}", hr);
          Cleanup();
          return false;
        }

        //add filewriter 
        Log.Info("DVR2MPG: Add FileWriter to graph");
        string monikerFileWrite =
          @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{3E8868CB-5FE8-402C-AA90-CB1AC6AE3240}";
        IBaseFilter fileWriterbase = Marshal.BindToMoniker(monikerFileWrite) as IBaseFilter;
        if (fileWriterbase == null)
        {
          Log.Warn("DVR2MPG: FAILED:Unable to create FileWriter");
          Cleanup();
          return false;
        }


        fileWriterFilter = fileWriterbase as IFileSinkFilter;
        if (fileWriterFilter == null)
        {
          Log.Warn("DVR2MPG: FAILED:Add unable to get IFileSinkFilter for filewriter");
          Cleanup();
          return false;
        }

        hr = graphBuilder.AddFilter(fileWriterbase, "FileWriter");
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED:Add FileWriter to filtergraph :0x{0:X}", hr);
          Cleanup();
          return false;
        }


        //connect output #0 of streambuffer source->powerdvd audio in
        //connect output #1 of streambuffer source->powerdvd video in
        Log.Info("DVR2MPG: connect streambuffer->multiplexer");
        IPin pinOut0, pinOut1;
        IPin pinIn0, pinIn1;
        pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0);
        pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1);

        pinIn0 = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Input, 0);
        pinIn1 = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Input, 1);
        if (pinOut0 == null || pinOut1 == null || pinIn0 == null || pinIn1 == null)
        {
          Log.Warn("DVR2MPG: FAILED:unable to get pins of muxer&source");
          Cleanup();
          return false;
        }

        bool usingAc3 = false;
        AMMediaType amAudio = new AMMediaType();
        amAudio.majorType = MediaType.Audio;
        amAudio.subType = MediaSubType.Mpeg2Audio;
        hr = pinOut0.Connect(pinIn1, amAudio);
        if (hr != 0)
        {
          amAudio.subType = MediaSubType.DolbyAC3;
          hr = pinOut0.Connect(pinIn1, amAudio);
          usingAc3 = true;
        }
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED: unable to connect audio pins: 0x{0:X}", hr);
          Cleanup();
          return false;
        }

        if (usingAc3)
          Log.Info("DVR2MPG: using AC3 audio");
        else
          Log.Info("DVR2MPG: using MPEG audio");

        AMMediaType amVideo = new AMMediaType();
        amVideo.majorType = MediaType.Video;
        amVideo.subType = MediaSubType.Mpeg2Video;
        hr = pinOut1.Connect(pinIn0, amVideo);
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED: unable to connect video pins: 0x{0:X}", hr);
          Cleanup();
          return false;
        }


        //connect output of powerdvd muxer->input of filewriter
        Log.Info("DVR2MPG: connect multiplexer->filewriter");
        IPin pinOut, pinIn;
        pinOut = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Output, 0);
        if (pinOut == null)
        {
          Log.Warn("DVR2MPG: FAILED:cannot get output pin of Cyberlink MPEG muxer :0x{0:X}", hr);
          Cleanup();
          return false;
        }
        pinIn = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 0);
        if (pinIn == null)
        {
          Log.Warn("DVR2MPG: FAILED:cannot get input pin of Filewriter :0x{0:X}", hr);
          Cleanup();
          return false;
        }
        AMMediaType mt = new AMMediaType();
        hr = pinOut.Connect(pinIn, mt);
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED:connect muxer->filewriter :0x{0:X}", hr);
          Cleanup();
          return false;
        }

        //set output filename
        string outputFileName = System.IO.Path.ChangeExtension(info.file, ".mpg");
        Log.Info("DVR2MPG: set output file to :{0}", outputFileName);
        mt.majorType = MediaType.Stream;
        mt.subType = MediaSubTypeEx.MPEG2;

        hr = fileWriterFilter.SetFileName(outputFileName, mt);
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED:unable to set filename for filewriter :0x{0:X}", hr);
          Cleanup();
          return false;
        }
        mediaControl = graphBuilder as IMediaControl;
        mediaSeeking = graphBuilder as IMediaSeeking;
        mediaEvt = graphBuilder as IMediaEventEx;
        Log.Info("DVR2MPG: start transcoding");
        hr = mediaControl.Run();
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED:unable to start graph :0x{0:X}", hr);
          Cleanup();
          return false;
        }
      }
      catch (Exception ex)
      {
        Log.Error("DVR2MPG: Unable create graph: {0}", ex.Message);
        Cleanup();
        return false;
      }
      return true;
    }
        /// <summary> Shut down capture </summary>
        private void CloseInterfaces()
        {
            int hr;

            try
            {
                if (m_mediaCtrl != null)
                {
                    // Stop the graph
                    hr = m_mediaCtrl.Stop();
                    m_mediaCtrl = null;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            #if DEBUG
            if (m_rot != null)
            {
                m_rot.Dispose();
            }
            #endif

            if (m_FilterGraph != null)
            {
                Marshal.ReleaseComObject(m_FilterGraph);
                m_FilterGraph = null;
            }
            GC.Collect();
        }
Пример #27
0
        private void StartCapture()
        {
            int hr;

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

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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

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

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

                SaveSizeInfo(sampGrabber);

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

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

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

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

                Start();
            }
            else
            {
                MessageBox.Show("File does not exist");
            }
        }
        /// <summary> build the capture graph for grabber. </summary>
        private void SetupGraph(string FileName)
        {
            int hr;

            ISampleGrabber sampGrabber = null;
            IBaseFilter baseGrabFlt = null;
            IBaseFilter capFilter = null;
            IBaseFilter nullrenderer = null;

            // Get the graphbuilder object
            m_FilterGraph = new FilterGraph() as IFilterGraph2;
            m_mediaCtrl = m_FilterGraph as IMediaControl;
            m_MediaEvent = m_FilterGraph as IMediaEvent;

            IMediaFilter mediaFilt = m_FilterGraph as IMediaFilter;

            try
            {
            #if DEBUG
                m_rot = new DsROTEntry(m_FilterGraph);
            #endif

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

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

                ConfigureSampleGrabber(sampGrabber);

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

                // ---------------------------------
                // Connect the file filter to the sample grabber

                // Hopefully this will be the video pin, we could check by reading it's mediatype
                IPin iPinOut = DsFindPin.ByDirection(capFilter, PinDirection.Output, 0);

                // Get the input pin from the sample grabber
                IPin iPinIn = DsFindPin.ByDirection(baseGrabFlt, PinDirection.Input, 0);

                hr = m_FilterGraph.Connect(iPinOut, iPinIn);
                DsError.ThrowExceptionForHR(hr);

                // Add the null renderer to the graph
                nullrenderer = new NullRenderer() as IBaseFilter;
                hr = m_FilterGraph.AddFilter(nullrenderer, "Null renderer");
                DsError.ThrowExceptionForHR(hr);

                // ---------------------------------
                // Connect the sample grabber to the null renderer

                iPinOut = DsFindPin.ByDirection(baseGrabFlt, PinDirection.Output, 0);
                iPinIn = DsFindPin.ByDirection(nullrenderer, PinDirection.Input, 0);

                hr = m_FilterGraph.Connect(iPinOut, iPinIn);
                DsError.ThrowExceptionForHR(hr);

                // Turn off the clock.  This causes the frames to be sent
                // thru the graph as fast as possible
                hr = mediaFilt.SetSyncSource(null);
                DsError.ThrowExceptionForHR(hr);

                // Read and cache the image sizes
                SaveSizeInfo(sampGrabber);
            }
            finally
            {
                if (capFilter != null)
                {
                    Marshal.ReleaseComObject(capFilter);
                    capFilter = null;
                }
                if (sampGrabber != null)
                {
                    Marshal.ReleaseComObject(sampGrabber);
                    sampGrabber = null;
                }
                if (nullrenderer != null)
                {
                    Marshal.ReleaseComObject(nullrenderer);
                    nullrenderer = null;
                }
            }
        }
Пример #29
0
        private void PlayMovieInWindow(string filename)
        {
            int hr = 0;

              if (filename == string.Empty)
            return;

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

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

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

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

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

              // Is this an audio-only file (no video component)?
              CheckVisibility();

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

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

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

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

            GetFrameStepInterface();
              }
              else
              {
            // Initialize the default player size and enable playback menu items
            hr = InitPlayerWindow();
            DsError.ThrowExceptionForHR(hr);

            EnablePlaybackMenu(true, MediaType.Audio);
              }

              // Complete window initialization
              CheckSizeMenu(menuFileSizeNormal);
              this.isFullScreen = false;
              this.currentPlaybackRate = 1.0;
              UpdateMainTitle();

            #if DEBUG
              rot = new DsROTEntry(this.graphBuilder);
            #endif

              this.Focus();

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

              this.currentState=PlayState.Running;
        }
Пример #30
0
 /// <summary>
 /// Resets the local graph resources to their
 /// default settings
 /// </summary>
 private void ResetLocalGraphResources()
 {
     m_basicAudio = null;
     m_mediaControl = null;
     m_mediaEvent = null;
 }
Пример #31
0
    private void CloseInterfaces()
    {
      try
      {
        lock (this)
        {
#if DEBUG
          if (rot != null)
          {
            rot.Dispose();
            rot = null;
          }
#endif

          //ChangeState(PlayState.Exiting);

          //// Release the thread (if the thread was started)
          //if (this.currentState != PlayState.Exiting)
          //{
          //  this.currentState = PlayState.Exiting;
          //  if (this.manualResetEvent != null)
          //  {
          //    manualResetEvent.Set();
          //    manualResetEvent.SafeWaitHandle.Dispose();
          //    manualResetEvent.Close();
          //    manualResetEvent = null;
          //  }
          //}
          //if (eventThread != null)
          //{
          //  eventThread.Abort();
          //}


          // Release and zero DirectShow interfaces
          if (this.mediaSeeking != null)
            this.mediaSeeking = null;
          //if (this.mediaEvent != null)
          //  this.mediaEvent = null;
          if (this.mediaControl != null)
            this.mediaControl = null;
          if (this.basicAudio != null)
            this.basicAudio = null;

          if (this.filterGraph != null)
          {
            //// End event thread.
            //int hr = ((IMediaEventSink)this.filterGraph).Notify(EventCode.UserAbort, IntPtr.Zero, IntPtr.Zero);
            //DsError.ThrowExceptionForHR(hr);
            ////EventCode code;
            ////hr = ((IMediaEvent)this.filterGraph).WaitForCompletion(0, out code);
            ////DsError.ThrowExceptionForHR(hr);
            //while (!threadCompleted)
            //{
            //  Thread.Sleep(2);
            //}
            Marshal.ReleaseComObject(this.filterGraph);
          }
          this.filterGraph = null;

          GC.Collect();
        }
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message, "Exception occured");
      }
    }
Пример #32
0
        // メソッド

        public CDirectShow(string fileName, IntPtr hWnd, bool bオーディオレンダラなし)
        {
            // 初期化。

            this.n幅px          = 0;
            this.n高さpx         = 0;
            this.b上下反転         = false;
            this.nスキャンライン幅byte = 0;
            this.nデータサイズbyte   = 0;
            this.b音声のみ         = false;
            this.graphBuilder  = null;
            this.MediaCtrl     = null;
            this.b再生中          = false;
            this.bループ再生        = false;


            // 静的リストに登録し、インスタンスIDを得る。

            CDirectShow.tインスタンスを登録する(this);


            // 並列処理準備。

            if (CDirectShow.n並列度 == 0)                         // 算出がまだなら算出する。
            {
                CDirectShow.n並列度 = Environment.ProcessorCount; // 並列度=CPU数とする。
            }
            unsafe
            {
                this.dgライン描画ARGB32 = new DGライン描画[CDirectShow.n並列度];
                this.dgライン描画XRGB32 = new DGライン描画[CDirectShow.n並列度];

                for (int i = 0; i < CDirectShow.n並列度; i++)
                {
                    this.dgライン描画ARGB32[i] = new DGライン描画(this.tライン描画ARGB32);
                    this.dgライン描画XRGB32[i] = new DGライン描画(this.tライン描画XRGB32);
                }
            }

            try
            {
                int hr = 0;


                // グラフビルダを生成。

                this.graphBuilder = (IGraphBuilder) new FilterGraph();
#if DEBUG
                // ROT への登録。
                this.rot = new DsROTEntry(graphBuilder);
#endif


                // QueryInterface。存在しなければ null。

                this.MediaCtrl    = this.graphBuilder as IMediaControl;
                this.MediaEventEx = this.graphBuilder as IMediaEventEx;
                this.MediaSeeking = this.graphBuilder as IMediaSeeking;
                this.BasicAudio   = this.graphBuilder as IBasicAudio;


                // IMemoryRenderer をグラフに挿入。

                AMMediaType mediaType = null;

                this.memoryRendererObject = new MemoryRenderer();
                this.memoryRenderer       = (IMemoryRenderer)this.memoryRendererObject;
                var baseFilter = (IBaseFilter)this.memoryRendererObject;

                hr = this.graphBuilder.AddFilter(baseFilter, "MemoryRenderer");
                DsError.ThrowExceptionForHR(hr);


                // fileName からグラフを自動生成。

                hr = this.graphBuilder.RenderFile(fileName, null);                      // IMediaControl.RenderFile() は推奨されない
                DsError.ThrowExceptionForHR(hr);


                // 音声のみ?

                {
                    IBaseFilter videoRenderer;
                    IPin        videoInputPin;
                    IBaseFilter audioRenderer;
                    IPin        audioInputPin;
#if MemoryRenderer
                    CDirectShow.tビデオレンダラとその入力ピンを探して返す(this.graphBuilder, out videoRenderer, out videoInputPin);
#else
                    CDirectShow.SearchMMRenderers(this.graphBuilder, out videoRenderer, out videoInputPin, out audioRenderer, out audioInputPin);
#endif
                    if (videoRenderer == null && audioRenderer != null)
                    {
                        this.b音声のみ = true;
                    }
                    else
                    {
                        C共通.tCOMオブジェクトを解放する(ref videoInputPin);
                        C共通.tCOMオブジェクトを解放する(ref videoRenderer);
                        C共通.tCOMオブジェクトを解放する(ref audioInputPin);
                        C共通.tCOMオブジェクトを解放する(ref audioRenderer);
                    }
                }


                // イメージ情報を取得。

                if (!this.b音声のみ)
                {
                    long n;
                    int  m;
                    this.memoryRenderer.GetWidth(out n);
                    this.n幅px = (int)n;
                    this.memoryRenderer.GetHeight(out n);
                    this.n高さpx = (int)n;
                    this.memoryRenderer.IsBottomUp(out m);
                    this.b上下反転 = (m != 0);
                    this.memoryRenderer.GetBufferSize(out n);
                    this.nデータサイズbyte   = (int)n;
                    this.nスキャンライン幅byte = (int)this.nデータサイズbyte / this.n高さpx;
                    // C共通.tCOMオブジェクトを解放する( ref baseFilter );		なんかキャスト元のオブジェクトまで解放されるので解放禁止。
                }


                // グラフを修正する。

                if (bオーディオレンダラなし)
                {
                    WaveFormat dummy1;
                    byte[]     dummy2;
                    CDirectShow.tオーディオレンダラをNullレンダラに変えてフォーマットを取得する(this.graphBuilder, out dummy1, out dummy2);
                }


                // その他の処理。

                this.t再生準備開始();                 // 1回以上 IMediaControl を呼び出してないと、IReferenceClock は取得できない。
                this.t遷移完了まで待って状態を取得する();       // 完全に Pause へ遷移するのを待つ。(環境依存)


                // イベント用ウィンドウハンドルを設定。

                this.MediaEventEx.SetNotifyWindow(hWnd, (int)WM_DSGRAPHNOTIFY, new IntPtr(this.nインスタンスID));
            }
#if !DEBUG
            catch (Exception e)
            {
                C共通.t例外の詳細をログに出力する(e);
                this.Dispose();
                throw;                  // 例外発出。
            }
#endif
            finally
            {
            }
        }