Exemple #1
0
        protected void UpdateCurrentPosition()
        {
            if (_mediaSeeking == null)
            {
                return;
            }
            //GetCurrentPosition(): Returns stream position.
            //Stream position:The current playback position, relative to the content start
            long   lStreamPos;
            double fCurrentPos;

            _mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position
            fCurrentPos  = lStreamPos;
            fCurrentPos /= 10000000d;
            _currentPos  = fCurrentPos;

            long   lContentStart, lContentEnd;
            double fContentStart, fContentEnd;

            _mediaSeeking.GetAvailable(out lContentStart, out lContentEnd);
            //_mediaSeeking.GetDuration(out  lDuration);
            //mediaPos.get_Duration(out duration);

            fContentStart  = lContentStart;
            fContentEnd    = lContentEnd;
            fContentStart /= 10000000d;
            fContentEnd   /= 10000000d;
            //duration=lDuration;
            //duration /= 10000000d;
            //Log.Info("{0} {1} {2}  ({3}) {4} {5}", fCurrentPos, fContentStart, fContentEnd, _currentPos, lDuration,duration);
            fContentEnd -= fContentStart;
            _duration    = fContentEnd;
        }
Exemple #2
0
    public long CurrentPosition()
    {
        // stream time in graph
        IMediaSeeking pMS  = m_pGraph as IMediaSeeking;
        long          tNow = 0;

        pMS.GetCurrentPosition(out tNow);
        return(tNow + m_tStart);
    }
Exemple #3
0
        public void GetCurrentPosition(out long pTimeNow)
        {
            if (m_pSeek == null)
            {
                throw new COMException("No seek pointer", E_Unexpected);
            }

            int hr = m_pSeek.GetCurrentPosition(out pTimeNow);

            DsError.ThrowExceptionForHR(hr);
        }
        public static int getCurPos(IMediaSeeking mediaSeeking, double fps)
        {
            if (mediaSeeking == null) return 1;
            long cur;
            mediaSeeking.GetCurrentPosition(out cur);

            if (!isInFrames(mediaSeeking))
                cur = refTime2frame(cur,fps);

            return (int)cur;
        }
Exemple #5
0
        private void updateTimeBarThread()
        {
            long time;
            int  volu;

            while (true)
            {
                try {
                    MediaSeeking.GetCurrentPosition(out time);

                    BasicAudio.get_Volume(out volu);

                    this.BeginInvoke(new MethodInvoker(() => { trackBar1.Value = (int)time; }));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

                Thread.Sleep(1000);
            }
        }
Exemple #6
0
        /// <summary>
        /// Updates the Output Frame data using data from the video stream. Call this in Game.Update().
        /// </summary>
        public void Update()
        {
            // Remove the OutputFrame from the GraphicsDevice to prevent an InvalidOperationException on the SetData line.
            if (outputFrame.GraphicsDevice.Textures[0] == outputFrame)
            {
                outputFrame.GraphicsDevice.Textures[0] = null;
            }

            // Set video data into the Output Frame
            outputFrame.SetData <byte>(videoFrameBytes);

            // Update current position read-out
            DsError.ThrowExceptionForHR(ms.GetCurrentPosition(out currentPosition));
        }
 public virtual HRESULT StepForward()
 {
     if (m_FrameStep != null)
     {
         if (!IsPaused)
         {
             Pause();
         }
         int hr = m_FrameStep.Step(1, null);
         if (hr < 0)
         {
             long _time;
             hr = m_MediaSeeking.GetCurrentPosition(out _time);
             DsLong   _stop = (long)0;
             TimeSpan _ts   = new TimeSpan(0, 0, 1);
             _time += _ts.Ticks / 20;
             DsLong _current = _time;
             hr = m_MediaSeeking.SetPositions(_current, AMSeekingSeekingFlags.AbsolutePositioning, _stop, AMSeekingSeekingFlags.NoPositioning);
         }
         return((HRESULT)hr);
     }
     return((HRESULT)E_POINTER);
 }
 /// <summary>
 /// Timer Tick Event that updates time slider positions during playback
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void timeSliderTimer_Tick(object sender, EventArgs e)
 {
     if (_mediaSeeking != null)
     {
         try
         {
             long pos = 0;
             _mediaSeeking.GetCurrentPosition(out pos);
             _timeSliderControl.Pos = (int)(pos / 10000);
         }
         catch
         {
             timeSliderTimer.Enabled = false;
         }
     }
 }
Exemple #9
0
        public int Percentage()
        {
            if (mediaSeeking == null)
            {
                return(100);
            }
            long lCurrent;

            mediaSeeking.GetCurrentPosition(out lCurrent);
            float percent = ((float)lCurrent) / ((float)m_dDuration);

            percent *= 50.0f;
            if (percent > 100)
            {
                percent = 100;
            }
            return((int)percent);
        }
Exemple #10
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (_IsScrolling)
            {
                return;
            }
            // If the player can seek, update the seek bar with the current position.
            if (_mediaSeek != null)
            {
                //            if (mediaSeek.GetCapabilitiesControl..CanSeek())
                //            {
                long timeNow;
                try
                {
                    int hr = _mediaSeek.GetCurrentPosition(out timeNow);
                    DsError.ThrowExceptionForHR(hr);
                    timeNow = timeNow + (long)(_offsetseek * ONE_MSEC);
                    TimeSpan duration = new TimeSpan(timeNow);
                    DateTime dt       = new DateTime(duration.Ticks);
                    lblTime.Text = String.Format("{0:HH:mm:ss}", dt);
                    if ((int)(timeNow / ONE_MSEC) < seekbar.Maximum)
                    {
                        seekbar.Value = (int)(timeNow / ONE_MSEC);
                    }
                    else
                    {
                        btnStop_Click(null, null);
                    }

                    TimeSpan t1 = TimeSpan.FromMilliseconds(seekbar.Value);
                    if (mvs.OffsetTime.Trim().Length > 0)
                    {
                        TimeSpan t2 = TimeSpan.Parse(mvs.OffsetTime);
                        t1 = t1.Add(t2);
                        //                DvdHMSFTimeCode t3 = ConvertToDvdHMSFTimeCode(t1);
                        label3.Text = t1.ToString();
                    }
                }
                catch (Exception ex)
                {
                    logger.ErrorException("Error in play position : \r\n\r\n", ex);
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Updates the Output Frame data using data from the video stream. Call this in Game.Update().
        /// </summary>
        public void Update()
        {
            // Set video data into the Output Frame
            DataStream    ds;
            DataRectangle dr = outputFrame.LockRectangle(0, LockFlags.Discard, out ds);

            int bytesPerRow    = videoWidth * 4;
            int skipBytesInRow = dr.Pitch - bytesPerRow;
            int offset         = 0;

            for (int j = 0; j < videoHeight; j++)
            {
                ds.WriteRange(videoFrameBytes, offset, bytesPerRow);
                ds.Seek(skipBytesInRow, System.IO.SeekOrigin.Current);
                offset += bytesPerRow;
            }

            //ds.WriteRange(videoFrameBytes);

            /*
             * for (int j = 0; j < h; j++)
             * {
             * for (int i = 0; i < dr.Pitch; i++)
             * {
             * if (i < w * 4)
             *   ds.WriteByte(videoFrameBytes[j * w * 4 + i]);
             * else
             *   ds.WriteByte(255);
             * }
             * }     */

            outputFrame.UnlockRectangle(0);

            //BaseTexture.ToFile(outputFrame, "c:\\video3.png", ImageFileFormat.Png);

            /*
             * System.IO.FileStream fs = System.IO.File.Create("c:\\video2.rgb");
             * fs.Write(videoFrameBytes, 0, videoFrameBytes.Length);
             * fs.Dispose();
             */

            // Update current position read-out
            m_mediaSeeking.GetCurrentPosition(out currentPosition);
        }
Exemple #12
0
        // Set the position of the graph to a specified TimeSpan
        protected void SeekGraphToTime(TimeSpan seekTime)
        {
            SendDebugMessage("Seeking graph to time...");
            int           hr;
            IMediaControl mc = (IMediaControl)currentFilterGraph;
            // Stop graph if not stopped
            FilterState fs;

            mc.GetState(50, out fs);
            if (fs != FilterState.Stopped)
            {
                if (fs != FilterState.Stopped)
                {
                    mc.Stop();
                }
            }

            long   timeInSeconds          = (long)seekTime.TotalSeconds;
            DsLong dsTimeIn100NanoSeconds = DsLong.FromInt64(timeInSeconds * 10000000);

            SendDebugMessage("Setting position to " + dsTimeIn100NanoSeconds.ToInt64().ToString());
            long pos;

            if (UsingSBEFilter)
            {
                // IStreamBufferMediaSeeking is used directly on the source filter   http://msdn.microsoft.com/en-us/library/dd694950(v=vs.85).aspx
                IStreamBufferMediaSeeking mSeek = (IStreamBufferMediaSeeking)currentSBEfilter;
                hr = mSeek.SetPositions(dsTimeIn100NanoSeconds, AMSeekingSeekingFlags.AbsolutePositioning, 0, AMSeekingSeekingFlags.NoPositioning);
                DsError.ThrowExceptionForHR(hr);
                mSeek.GetCurrentPosition(out pos);
            }
            else
            {
                // IMediaSeeking is used on the filter graph which distributes the calls
                IMediaSeeking mSeek = (IMediaSeeking)currentFilterGraph;
                hr = mSeek.SetPositions(dsTimeIn100NanoSeconds, AMSeekingSeekingFlags.AbsolutePositioning, 0, AMSeekingSeekingFlags.NoPositioning);
                DsError.ThrowExceptionForHR(hr);
                mSeek.GetCurrentPosition(out pos);
            }

            SendDebugMessage("New pos is " + pos.ToString());
        }
Exemple #13
0
 /// <summary>
 /// Updates the Output Frame data using data from the video stream. Call this in Game.Update().
 /// </summary>
 public void Update()
 {
     //using (MyRenderStats.Measure("VideoUpdate-CopyTexture", MyStatTypeEnum.Max))
     {
         // Set video data into the Output Frame
         if (m_videoDataRgba.RefreshRead())
         {
         }
         // now for some reason after changing to fullscreen it's not refreshed, so we will always call it
         {
             OnFrame(m_videoDataRgba.Read);
         }
         // Update current position read-out
         m_mediaSeeking.GetCurrentPosition(out currentPosition);
         if (currentPosition >= videoDuration)
         {
             currentState = VideoState.Stopped;
         }
     }
 }
Exemple #14
0
        /// <summary>
        /// Queries the current video source for its capabilities regarding seeking and time info.
        /// The graph should be fully constructed for accurate information
        /// </summary>
        protected void QuerySeekingCapabilities()
        {
            try
            {
                _mediaSeeking.SetTimeFormat(TimeFormat.MediaTime);
                //get capabilities from the graph, and see what it supports that interests us
                AMSeekingSeekingCapabilities caps;
                int    r       = _mediaSeeking.GetCapabilities(out caps);
                long   lTest   = 0;
                double dblTest = 0;
                if (r != 0)
                {
                    _seek_canGetCurrentPos = false;
                    _seek_canSeek          = false;
                    _seek_canGetDuration   = false;
                }
                else    //if we were able to read the capabilities, then determine if the capability works, both by checking the
                // advertisement, and actually trying it out.
                {
                    _seek_canSeek = ((caps & AMSeekingSeekingCapabilities.CanSeekAbsolute) == AMSeekingSeekingCapabilities.CanSeekAbsolute) &&
                                    (_mediaSeeking.SetPositions(0, AMSeekingSeekingFlags.AbsolutePositioning,
                                                                null, AMSeekingSeekingFlags.NoPositioning) == 0);

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

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

                //check capabilities for the IMediaPosition interface
                _pos_canSeek          = (_mediaPosition.put_CurrentPosition(0) == 0);
                _pos_canGetDuration   = (_mediaPosition.get_Duration(out dblTest) == 0);
                _pos_canGetCurrentPos = (_mediaPosition.get_CurrentPosition(out dblTest) == 0);
            }
            catch (Exception)
            {
                _seek_canSeek = false;
                _pos_canSeek  = false;
            }
        }
Exemple #15
0
        /// <summary>
        /// Polls the graph for various data about the media that is playing
        /// </summary>
        protected override void OnGraphTimerTick()
        {
            /* Polls the current position */
            if (m_mediaSeeking != null)
            {
                long lCurrentPos;

                int hr = m_mediaSeeking.GetCurrentPosition(out lCurrentPos);

                if (hr == 0)
                {
                    if (lCurrentPos != m_currentPosition)
                    {
                        m_currentPosition = lCurrentPos;
                        InvokeMediaPositionChanged(null);
                    }
                }
            }

            base.OnGraphTimerTick();
        }
Exemple #16
0
        /// <summary>
        /// Step a specified number of frames in the feed (this function only applies to a videw file feed).
        /// </summary>
        /// <param name="nFrames">Specifies the number of frames to step.</param>
        /// <returns>After a successful step <i>true</i> is returned, otherwise when ignored or not running <i>false</i> is returned.</returns>
        public bool Step(int nFrames)
        {
            if (m_mediaSeek == null)
            {
                return(false);
            }

            if (m_bRunning)
            {
                return(false);
            }

            if (m_videoFrameStep != null)
            {
                int hr = m_videoFrameStep.Step(nFrames, null);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }
            }
            else
            {
                long lPosition;
                int  hr = m_mediaSeek.GetCurrentPosition(out lPosition);

                long lStep        = m_videoInfoHeader.AvgTimePerFrame * nFrames;
                long lNewPosition = lPosition + lStep;

                if (lNewPosition > Duration)
                {
                    lNewPosition = Duration;
                }

                SetPosition(lNewPosition);
            }

            return(true);
        }
Exemple #17
0
        private void timer_Tick(object sender, EventArgs e)
        {
            if (updating)
            {
                return;
            }

            updating = true;

            if (mediaSeeking != null && trackBar.Enabled)
            {
                long currentPosition;

                mediaSeeking.GetCurrentPosition(out currentPosition);
                trackBar.Value = checked ((int)(currentPosition / timeScalingFactor));
            }
            else
            {
                trackBar.Value = 0;
            }

            updating = false;
        }
Exemple #18
0
        private bool CheckGraphConversion(ref IMediaSeeking mediaSeeking)
        {
            int         hr;
            IMediaEvent mediaEvent = (IMediaEvent)currentFilterGraph;

            // Check the graph / conversion is going ok, and raise any progress events
            EventCode statusCode;

            hr = mediaEvent.WaitForCompletion(100, out statusCode);
            switch (statusCode)
            {
            case EventCode.Complete:
                return(true);

            case 0:      // Still going - fire event with an update on where we are
                if (mediaSeeking != null)
                {
                    long curPos;
                    mediaSeeking.GetCurrentPosition(out curPos);
                    long length;
                    mediaSeeking.GetDuration(out length);
                    double progress = curPos * 100.0 / (double)length;
                    if (ConversionProgressChanged != null)
                    {
                        ConversionProgressChanged(new object(), new ProgressChangedEventArgs(progress));
                    }
                }
                return(false);

            default:      // Error
                EventCode tryCode;
                IntPtr    lp1, lp2;
                hr = mediaEvent.GetEvent(out tryCode, out lp1, out lp2, 200);
                DsError.ThrowExceptionForHR(hr);
                throw new Exception(statusCode.ToString());
            }
        }
Exemple #19
0
        /// <summary>
        /// Test the functions that read the current position
        /// </summary>
        void TestPosition()
        {
            int  hr;
            long pCurrent1, pStop1, pDuration1;
            long pCurrent2, pStop2;
            long pEarliest, pLatest;

            // Read the current play position
            hr = m_ims.GetCurrentPosition(out pCurrent1);
            Marshal.ThrowExceptionForHR(hr);

            // Read the current stop position
            hr = m_ims.GetStopPosition(out pStop1);
            Marshal.ThrowExceptionForHR(hr);

            // Read the duraton (probably related to StopPosition - Position
            hr = m_ims.GetDuration(out pDuration1);
            Marshal.ThrowExceptionForHR(hr);

            // Read both current and stop positions
            hr = m_ims.GetPositions(out pCurrent2, out pStop2);
            Marshal.ThrowExceptionForHR(hr);

            // Get the cached range of values
            hr = m_ims.GetAvailable(out pEarliest, out pLatest);
            Marshal.ThrowExceptionForHR(hr);

            // Since we aren't playing, current should be 0, stop &
            // duration should be the same (the length of the clip)
            Debug.Assert(pCurrent1 == 0, "CurrentPosition");
            Debug.Assert(pStop1 == pDuration1, "Stop, Duration");
            Debug.Assert(pCurrent1 == pCurrent2, "GetPositions");
            Debug.Assert(pStop1 == pStop2, "CurrentPosition stop");
            Debug.Assert(pEarliest == pCurrent1, "CurrentPosition stop");
            Debug.Assert(pLatest == pStop2, "CurrentPosition stop");
        }
Exemple #20
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() != ".ts" && ext.ToLower() != ".mpg")
            {
                Log.Info("TSReader2MP4: wrong file format");
                return(false);
            }
            try
            {
                graphBuilder = (IGraphBuilder) new FilterGraph();
                _rotEntry    = new DsROTEntry((IFilterGraph)graphBuilder);
                Log.Info("TSReader2MP4: add filesource");
                TsReader reader = new TsReader();
                tsreaderSource = (IBaseFilter)reader;
                IBaseFilter filter = (IBaseFilter)tsreaderSource;
                graphBuilder.AddFilter(filter, "TSReader Source");
                IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource;
                Log.Info("TSReader2MP4: load file:{0}", info.file);
                int hr = fileSource.Load(info.file, null);
                //add audio/video codecs
                string strVideoCodec     = "";
                string strH264VideoCodec = "";
                string strAudioCodec     = "";
                string strAACAudioCodec  = "";
                using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
                {
                    strVideoCodec     = xmlreader.GetValueAsString("mytv", "videocodec", "");
                    strAudioCodec     = xmlreader.GetValueAsString("mytv", "audiocodec", "");
                    strAACAudioCodec  = xmlreader.GetValueAsString("mytv", "aacaudiocodec", "");
                    strH264VideoCodec = xmlreader.GetValueAsString("mytv", "h264videocodec", "");
                }
                //Find the type of decoder required for the output video & audio pins on TSReader.
                Log.Info("TSReader2MP4: find tsreader compatible audio/video decoders");
                IPin pinOut0, pinOut1;
                IPin pinIn0, pinIn1;
                pinOut0 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 0); //audio
                pinOut1 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 1); //video
                if (pinOut0 == null || pinOut1 == null)
                {
                    Log.Error("TSReader2MP4: FAILED: unable to get output pins of tsreader");
                    Cleanup();
                    return(false);
                }
                bool            usingAAC = false;
                IEnumMediaTypes enumMediaTypes;
                hr = pinOut0.EnumMediaTypes(out enumMediaTypes);
                while (true)
                {
                    AMMediaType[] mediaTypes = new AMMediaType[1];
                    int           typesFetched;
                    hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched);
                    if (hr != 0 || typesFetched == 0)
                    {
                        break;
                    }
                    if (mediaTypes[0].majorType == MediaType.Audio && mediaTypes[0].subType == MediaSubType.LATMAAC)
                    {
                        Log.Info("TSReader2MP4: found LATM AAC audio out pin on tsreader");
                        usingAAC = true;
                    }
                }
                bool usingH264 = false;
                hr = pinOut1.EnumMediaTypes(out enumMediaTypes);
                while (true)
                {
                    AMMediaType[] mediaTypes = new AMMediaType[1];
                    int           typesFetched;
                    hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched);
                    if (hr != 0 || typesFetched == 0)
                    {
                        break;
                    }
                    if (mediaTypes[0].majorType == MediaType.Video && mediaTypes[0].subType == AVC1)
                    {
                        Log.Info("TSReader2MP4: found H.264 video out pin on tsreader");
                        usingH264 = true;
                    }
                }
                //Add the type of decoder required for the output video & audio pins on TSReader.
                Log.Info("TSReader2MP4: add audio/video decoders to graph");
                if (usingH264 == false)
                {
                    Log.Info("TSReader2MP4: add mpeg2 video decoder:{0}", strVideoCodec);
                    VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec);
                    if (VideoCodec == null)
                    {
                        Log.Error("TSReader2MP4: unable to add mpeg2 video decoder");
                        Cleanup();
                        return(false);
                    }
                }
                else
                {
                    Log.Info("TSReader2MP4: add h264 video codec:{0}", strH264VideoCodec);
                    VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec);
                    if (VideoCodec == null)
                    {
                        Log.Error("TSReader2MP4: FAILED:unable to add h264 video codec");
                        Cleanup();
                        return(false);
                    }
                }
                if (usingAAC == false)
                {
                    Log.Info("TSReader2MP4: add mpeg2 audio codec:{0}", strAudioCodec);
                    AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec);
                    if (AudioCodec == null)
                    {
                        Log.Error("TSReader2MP4: FAILED:unable to add mpeg2 audio codec");
                        Cleanup();
                        return(false);
                    }
                }
                else
                {
                    Log.Info("TSReader2MP4: add aac audio codec:{0}", strAACAudioCodec);
                    AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec);
                    if (AudioCodec == null)
                    {
                        Log.Error("TSReader2MP4: FAILED:unable to add aac audio codec");
                        Cleanup();
                        return(false);
                    }
                }
                Log.Info("TSReader2MP4: connect tsreader->audio/video decoders");
                //connect output #0 (audio) of tsreader->audio decoder input pin 0
                //connect output #1 (video) of tsreader->video decoder input pin 0
                pinIn0 = DsFindPin.ByDirection(AudioCodec, PinDirection.Input, 0); //audio
                pinIn1 = DsFindPin.ByDirection(VideoCodec, PinDirection.Input, 0); //video
                if (pinIn0 == null || pinIn1 == null)
                {
                    Log.Error("TSReader2MP4: FAILED: unable to get pins of video/audio codecs");
                    Cleanup();
                    return(false);
                }
                hr = graphBuilder.Connect(pinOut0, pinIn0);
                if (hr != 0)
                {
                    Log.Error("TSReader2MP4: FAILED: unable to connect audio pins :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
                hr = graphBuilder.Connect(pinOut1, pinIn1);
                if (hr != 0)
                {
                    Log.Error("TSReader2MP4: FAILED: unable to connect video pins :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
                //add encoders, muxer & filewriter
                if (!AddCodecs(graphBuilder, info))
                {
                    return(false);
                }
                //setup graph controls
                mediaControl = graphBuilder as IMediaControl;
                mediaSeeking = tsreaderSource as IMediaSeeking;
                mediaEvt     = graphBuilder as IMediaEventEx;
                mediaPos     = graphBuilder as IMediaPosition;
                //get file duration
                Log.Info("TSReader2MP4: Get duration of recording");
                long lTime = 5 * 60 * 60;
                lTime *= 10000000;
                long pStop = 0;
                hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                               AMSeekingSeekingFlags.NoPositioning);
                if (hr == 0)
                {
                    long lStreamPos;
                    mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position
                    m_dDuration = lStreamPos;
                    lTime       = 0;
                    mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                              AMSeekingSeekingFlags.NoPositioning);
                }
                double duration = m_dDuration / 10000000d;
                Log.Info("TSReader2MP4: recording duration: {0}", MediaPortal.Util.Utils.SecondsToHMSString((int)duration));
                //run the graph to initialize the filters to be sure
                hr = mediaControl.Run();
                if (hr != 0)
                {
                    Log.Error("TSReader2MP4: FAILED: unable to start graph :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
                int maxCount = 20;
                while (true)
                {
                    long lCurrent;
                    mediaSeeking.GetCurrentPosition(out lCurrent);
                    double dpos = (double)lCurrent;
                    dpos /= 10000000d;
                    System.Threading.Thread.Sleep(100);
                    if (dpos >= 2.0d)
                    {
                        break;
                    }
                    maxCount--;
                    if (maxCount <= 0)
                    {
                        break;
                    }
                }
                mediaControl.Stop();
                FilterState state;
                mediaControl.GetState(500, out state);
                GC.Collect();
                GC.Collect();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                graphBuilder.RemoveFilter(mp4Muxer);
                graphBuilder.RemoveFilter(h264Encoder);
                graphBuilder.RemoveFilter(aacEncoder);
                graphBuilder.RemoveFilter((IBaseFilter)fileWriterFilter);
                if (!AddCodecs(graphBuilder, info))
                {
                    return(false);
                }
                //Set Encoder quality & Muxer settings
                if (!EncoderSet(graphBuilder, info))
                {
                    return(false);
                }
                //start transcoding - run the graph
                Log.Info("TSReader2MP4: start transcoding");
                //setup flow control
                //need to leverage CBAsePin, CPullPin & IAsyncReader methods.
                IAsyncReader synchVideo = null;
                mediaSample = VideoCodec as IMediaSample;
                hr          = synchVideo.SyncReadAligned(mediaSample);
                //So we only parse decoder output whent the encoders are ready.
                hr = mediaControl.Run();
                if (hr != 0)
                {
                    Log.Error("TSReader2MP4: FAILED:unable to start graph :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error("TSReader2MP4: Unable create graph: {0}", ex.Message);
                Cleanup();
                return(false);
            }
            return(true);
        }
Exemple #21
0
        /// <summary>Runs the graph</summary>
        /// <param name="graphBuilder">The graph to be run.</param>
        /// <param name="seekableFilter">The filter to use for computing percent complete. Must implement IMediaSeeking.</param>
        protected void RunGraph(IGraphBuilder graphBuilder, IBaseFilter seekableFilter)
        {
            // Get the necessary control and event interfaces
            IMediaControl mediaControl = (IMediaControl)graphBuilder;
            IMediaEvent   mediaEvent   = (IMediaEvent)graphBuilder;

            // Get the media seeking interface to use for computing status and progress updates
            IMediaSeeking mediaSeeking = seekableFilter as IMediaSeeking;

            if (!CanGetPositionAndDuration(mediaSeeking))
            {
                mediaSeeking = graphBuilder as IMediaSeeking;
                if (!CanGetPositionAndDuration(mediaSeeking))
                {
                    mediaSeeking = null;
                }
            }

            // Publish the graph to the running object table and to a temporary file for examination/debugging purposes
            using (new GraphPublisher(graphBuilder, Path.GetTempPath() + Guid.NewGuid().ToString("N") + ".grf"))
            {
                // Run the graph
                mediaControl.Run();
                try
                {
                    OnProgressChanged(0);                     // initial progress update stating 0% done
                    bool done = false;
                    while (!CancellationPending && !done)     // continue until we're done/cancelled
                    {
                        // Poll to see how we're doing
                        EventCode statusCode = EventCode.None;
                        int       hr         = mediaEvent.WaitForCompletion(PollFrequency, out statusCode);
                        switch (statusCode)
                        {
                        case EventCode.Complete:
                            done = true;
                            break;

                        case EventCode.None:
                            // Get an update on where we are with the conversion
                            if (mediaSeeking != null)
                            {
                                ulong  curPos   = mediaSeeking.GetCurrentPosition();
                                ulong  length   = mediaSeeking.GetDuration();
                                double progress = curPos * 100.0 / (double)length;
                                if (progress > 0)
                                {
                                    OnProgressChanged(progress);
                                }
                            }
                            break;

                        default:
                            // Error, so throw exception
                            throw new DirectShowException(hr, null);
                        }
                    }
                    OnProgressChanged(100);                     // final progress update stating 100% done
                }
                finally
                {
                    // We're done converting, so stop the graph
                    mediaControl.Stop();
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// Worker thread.
        /// </summary>
        ///
        private void WorkerThread()
        {
            ReasonToFinishPlaying reasonToStop = ReasonToFinishPlaying.StoppedByUser;

            // grabber
            Grabber grabber = new Grabber(this);

            // objects
            object graphObject   = null;
            object grabberObject = null;

            // interfaces
            IGraphBuilder  graph         = null;
            IBaseFilter    sourceBase    = null;
            IBaseFilter    grabberBase   = null;
            ISampleGrabber sampleGrabber = null;
            IMediaControl  mediaControl  = null;

            IMediaEventEx mediaEvent   = null;
            IMediaSeeking mediaSeeking = null;

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

                // create filter graph
                graphObject = Activator.CreateInstance(type);
                graph       = (IGraphBuilder)graphObject;

                // create source device's object
                graph.AddSourceFilter(_fileName, "source", out sourceBase);
                if (sourceBase == null)
                {
                    throw new ApplicationException("Failed creating source filter");
                }

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

                // create sample grabber
                grabberObject = Activator.CreateInstance(type);
                sampleGrabber = (ISampleGrabber)grabberObject;
                grabberBase   = (IBaseFilter)grabberObject;

                // add grabber filters to graph
                graph.AddFilter(grabberBase, "grabber");

                // set media type
                AMMediaType mediaType = new AMMediaType
                {
                    MajorType = MediaType.Video,
                    SubType   = MediaSubType.RGB24
                };
                sampleGrabber.SetMediaType(mediaType);

                // connect pins
                int pinToTry = 0;

                IPin inPin  = Tools.GetInPin(grabberBase, 0);
                IPin outPin = null;

                // find output pin acceptable by sample grabber
                while (true)
                {
                    outPin = Tools.GetOutPin(sourceBase, pinToTry);

                    if (outPin == null)
                    {
                        Marshal.ReleaseComObject(inPin);
                        throw new ApplicationException("Did not find acceptable output video pin in the given source");
                    }

                    if (graph.Connect(outPin, inPin) < 0)
                    {
                        Marshal.ReleaseComObject(outPin);
                        outPin = null;
                        pinToTry++;
                    }
                    else
                    {
                        break;
                    }
                }

                Marshal.ReleaseComObject(outPin);
                Marshal.ReleaseComObject(inPin);

                // get media type
                if (sampleGrabber.GetConnectedMediaType(mediaType) == 0)
                {
                    VideoInfoHeader vih = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.FormatPtr, typeof(VideoInfoHeader));

                    grabber.Width  = vih.BmiHeader.Width;
                    grabber.Height = vih.BmiHeader.Height;
                    mediaType.Dispose();
                }

                // let's do rendering, if we don't need to prevent freezing
                if (!_preventFreezing)
                {
                    // render pin
                    graph.Render(Tools.GetOutPin(grabberBase, 0));

                    // configure video window
                    IVideoWindow window = (IVideoWindow)graphObject;
                    window.put_AutoShow(false);
                    window = null;
                }

                // configure sample grabber
                sampleGrabber.SetBufferSamples(false);
                sampleGrabber.SetOneShot(false);
                sampleGrabber.SetCallback(grabber, 1);

                // disable clock, if someone requested it
                if (!_referenceClockEnabled)
                {
                    IMediaFilter mediaFilter = (IMediaFilter)graphObject;
                    mediaFilter.SetSyncSource(null);
                }

                // get media control
                mediaControl = (IMediaControl)graphObject;

                // get media events' interface
                mediaEvent = (IMediaEventEx)graphObject;

                // Get media seeking & check seeking capability
                mediaSeeking = (IMediaSeeking)graphObject;
                mediaSeeking.GetDuration(out _duration);
                _onVideoLoad(_duration);
                const SeekingCapabilities caps = SeekingCapabilities.CanSeekAbsolute | SeekingCapabilities.CanGetDuration;
                SeekingCapabilities       canSeekCap;
                int hr = mediaSeeking.GetCapabilities(out canSeekCap);
                if (hr < 0)
                {
                    throw new ApplicationException("Failed getting seeking capabilities");
                }
                _isSeekEnabled = (canSeekCap & caps) == caps;

                // run
                mediaControl.Run();
                IsPlaying = true;
                do
                {
                    // GetCurrentTime
                    if (_isGetCurrentTime)
                    {
                        mediaSeeking.GetCurrentPosition(out _currentGetTime);
                        _isGetCurrentTime = false;
                    }
                    if (IsSetPause)
                    {
                        mediaControl.Pause();
                        IsSetPause = false;
                        IsPlaying  = false;
                    }
                    if (IsSetPlay)
                    {
                        mediaControl.Run();
                        IsSetPlay = false;
                        IsPlaying = true;
                    }
                    // SetCurrentTime
                    if (_isSetCurrentTime)
                    {
                        long stop = 0;
                        mediaSeeking.SetPositions(ref _currentSetTime, SeekingFlags.AbsolutePositioning, ref stop,
                                                  SeekingFlags.NoPositioning);
                        _isSetCurrentTime = false;
                    }
                    IntPtr   p1;
                    IntPtr   p2;
                    DsEvCode code;
                    if (mediaEvent.GetEvent(out code, out p1, out p2, 0) >= 0)
                    {
                        mediaEvent.FreeEventParams(code, p1, p2);

                        if (code == DsEvCode.Complete)
                        {
                            reasonToStop = ReasonToFinishPlaying.EndOfStreamReached;
                            break;
                        }
                    }
                } while (!_stopEvent.WaitOne(100, false));
                IsPlaying = false;
                mediaControl.Stop();
            }
            catch (Exception exception)
            {
                // provide information to clients
                if (VideoSourceError != null)
                {
                    VideoSourceError(this, new VideoSourceErrorEventArgs(exception.Message));
                }
            }
            finally
            {
                // release all objects
                graph         = null;
                grabberBase   = null;
                sampleGrabber = null;
                mediaControl  = null;
                mediaEvent    = null;
                mediaSeeking  = null;

                if (graphObject != null)
                {
                    Marshal.ReleaseComObject(graphObject);
                    graphObject = null;
                }
                if (sourceBase != null)
                {
                    Marshal.ReleaseComObject(sourceBase);
                    sourceBase = null;
                }
                if (grabberObject != null)
                {
                    Marshal.ReleaseComObject(grabberObject);
                    grabberObject = null;
                }
            }

            if (PlayingFinished != null)
            {
                PlayingFinished(this, reasonToStop);
            }
        }
Exemple #23
0
 public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard)
 {
     try
     {
         if (!Supports(format))
         {
             return(false);
         }
         string ext = System.IO.Path.GetExtension(info.file);
         if (ext.ToLowerInvariant() != ".ts" && ext.ToLowerInvariant() != ".mpg")
         {
             Log.Info("TSReader2WMV: wrong file format");
             return(false);
         }
         Log.Info("TSReader2WMV: create graph");
         graphBuilder = (IGraphBuilder) new FilterGraph();
         _rotEntry    = new DsROTEntry((IFilterGraph)graphBuilder);
         Log.Info("TSReader2WMV: add filesource");
         TsReader reader = new TsReader();
         tsreaderSource = (IBaseFilter)reader;
         //ITSReader ireader = (ITSReader)reader;
         //ireader.SetTsReaderCallback(this);
         //ireader.SetRequestAudioChangeCallback(this);
         IBaseFilter filter = (IBaseFilter)tsreaderSource;
         graphBuilder.AddFilter(filter, "TSReader Source");
         IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource;
         Log.Info("TSReader2WMV: load file:{0}", info.file);
         int hr = fileSource.Load(info.file, null);
         //add audio/video codecs
         string strVideoCodec     = "";
         string strH264VideoCodec = "";
         string strAudioCodec     = "";
         string strAACAudioCodec  = "";
         using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
         {
             strVideoCodec     = xmlreader.GetValueAsString("mytv", "videocodec", "");
             strAudioCodec     = xmlreader.GetValueAsString("mytv", "audiocodec", "");
             strAACAudioCodec  = xmlreader.GetValueAsString("mytv", "aacaudiocodec", "");
             strH264VideoCodec = xmlreader.GetValueAsString("mytv", "h264videocodec", "");
         }
         //Find the type of decoder required for the output video & audio pins on TSReader.
         Log.Info("TSReader2WMV: find tsreader compatible audio/video decoders");
         IPin pinOut0, pinOut1;
         IPin pinIn0, pinIn1;
         pinOut0 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 0); //audio
         pinOut1 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 1); //video
         if (pinOut0 == null || pinOut1 == null)
         {
             Log.Error("TSReader2WMV: FAILED: unable to get output pins of tsreader");
             Cleanup();
             return(false);
         }
         bool            usingAAC = false;
         IEnumMediaTypes enumMediaTypes;
         hr = pinOut0.EnumMediaTypes(out enumMediaTypes);
         while (true)
         {
             AMMediaType[] mediaTypes = new AMMediaType[1];
             int           typesFetched;
             hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched);
             if (hr != 0 || typesFetched == 0)
             {
                 break;
             }
             if (mediaTypes[0].majorType == MediaType.Audio && mediaTypes[0].subType == MediaSubType.LATMAAC)
             {
                 Log.Info("TSReader2WMV: found LATM AAC audio out pin on tsreader");
                 usingAAC = true;
             }
         }
         bool usingH264 = false;
         hr = pinOut1.EnumMediaTypes(out enumMediaTypes);
         while (true)
         {
             AMMediaType[] mediaTypes = new AMMediaType[1];
             int           typesFetched;
             hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched);
             if (hr != 0 || typesFetched == 0)
             {
                 break;
             }
             if (mediaTypes[0].majorType == MediaType.Video && mediaTypes[0].subType == AVC1)
             {
                 Log.Info("TSReader2WMV: found H.264 video out pin on tsreader");
                 usingH264 = true;
             }
         }
         //Add the type of decoder required for the output video & audio pins on TSReader.
         Log.Info("TSReader2WMV: add audio/video decoders to graph");
         if (usingH264 == false)
         {
             Log.Info("TSReader2WMV: add mpeg2 video decoder:{0}", strVideoCodec);
             VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec);
             if (VideoCodec == null)
             {
                 Log.Error("TSReader2WMV: unable to add mpeg2 video decoder");
                 Cleanup();
                 return(false);
             }
         }
         else
         {
             Log.Info("TSReader2WMV: add h264 video codec:{0}", strH264VideoCodec);
             VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec);
             if (VideoCodec == null)
             {
                 Log.Error("TSReader2WMV: FAILED:unable to add h264 video codec");
                 Cleanup();
                 return(false);
             }
         }
         if (usingAAC == false)
         {
             Log.Info("TSReader2WMV: add mpeg2 audio codec:{0}", strAudioCodec);
             AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec);
             if (AudioCodec == null)
             {
                 Log.Error("TSReader2WMV: FAILED:unable to add mpeg2 audio codec");
                 Cleanup();
                 return(false);
             }
         }
         else
         {
             Log.Info("TSReader2WMV: add aac audio codec:{0}", strAACAudioCodec);
             AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec);
             if (AudioCodec == null)
             {
                 Log.Error("TSReader2WMV: FAILED:unable to add aac audio codec");
                 Cleanup();
                 return(false);
             }
         }
         Log.Info("TSReader2WMV: connect tsreader->audio/video decoders");
         //connect output #0 (audio) of tsreader->audio decoder input pin 0
         //connect output #1 (video) of tsreader->video decoder input pin 0
         pinIn0 = DsFindPin.ByDirection(AudioCodec, PinDirection.Input, 0); //audio
         pinIn1 = DsFindPin.ByDirection(VideoCodec, PinDirection.Input, 0); //video
         if (pinIn0 == null || pinIn1 == null)
         {
             Log.Error("TSReader2WMV: FAILED: unable to get pins of video/audio codecs");
             Cleanup();
             return(false);
         }
         hr = graphBuilder.Connect(pinOut0, pinIn0);
         if (hr != 0)
         {
             Log.Error("TSReader2WMV: FAILED: unable to connect audio pins :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         hr = graphBuilder.Connect(pinOut1, pinIn1);
         if (hr != 0)
         {
             Log.Error("TSReader2WMV: FAILED: unable to connect video pins :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv");
         if (!AddWmAsfWriter(outputFilename, quality, standard))
         {
             return(false);
         }
         Log.Info("TSReader2WMV: start pre-run");
         mediaControl = graphBuilder as IMediaControl;
         mediaSeeking = tsreaderSource as IMediaSeeking;
         mediaEvt     = graphBuilder as IMediaEventEx;
         mediaPos     = graphBuilder as IMediaPosition;
         //get file duration
         long lTime = 5 * 60 * 60;
         lTime *= 10000000;
         long pStop = 0;
         hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                        AMSeekingSeekingFlags.NoPositioning);
         if (hr == 0)
         {
             long lStreamPos;
             mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position
             m_dDuration = lStreamPos;
             lTime       = 0;
             mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                       AMSeekingSeekingFlags.NoPositioning);
         }
         double duration = m_dDuration / 10000000d;
         Log.Info("TSReader2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration));
         hr = mediaControl.Run();
         if (hr != 0)
         {
             Log.Error("TSReader2WMV: FAILED: unable to start graph :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         int maxCount = 20;
         while (true)
         {
             long lCurrent;
             mediaSeeking.GetCurrentPosition(out lCurrent);
             double dpos = (double)lCurrent;
             dpos /= 10000000d;
             System.Threading.Thread.Sleep(100);
             if (dpos >= 2.0d)
             {
                 break;
             }
             maxCount--;
             if (maxCount <= 0)
             {
                 break;
             }
         }
         Log.Info("TSReader2WMV: pre-run done");
         Log.Info("TSReader2WMV: Get duration of movie");
         mediaControl.Stop();
         FilterState state;
         mediaControl.GetState(500, out state);
         GC.Collect();
         GC.Collect();
         GC.Collect();
         GC.WaitForPendingFinalizers();
         Log.Info("TSReader2WMV: reconnect mpeg2 video codec->ASF WM Writer");
         graphBuilder.RemoveFilter(fileWriterbase);
         if (!AddWmAsfWriter(outputFilename, quality, standard))
         {
             return(false);
         }
         Log.Info("TSReader2WMV: Start transcoding");
         hr = mediaControl.Run();
         if (hr != 0)
         {
             Log.Error("TSReader2WMV:FAILED:unable to start graph :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
     }
     catch (Exception e)
     {
         // TODO: Handle exceptions.
         Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message);
         return(false);
     }
     return(true);
 }
        public override int Enable(int lIndex, AMStreamSelectEnableFlags dwFlags)
        {
            bool changed        = false;
            uint oldAudioStream = _streamParser.InputStream.AudioStream.StreamId;

            for (int index = 0; index < _streamParser.SelectableTracks.Count; index++)
            {
                var track = _streamParser.SelectableTracks[index];

                bool isEnabled = (
                    index == lIndex && dwFlags == AMStreamSelectEnableFlags.Enable || // the current index should be enabled
                    dwFlags == AMStreamSelectEnableFlags.EnableAll                    // all should be enabled
                    ) && dwFlags != AMStreamSelectEnableFlags.DisableAll;             // must not be "Disable All"

                changed |= _streamParser.InputStream.EnableStream((int)track.StreamId, isEnabled);
            }
            uint newAudioStream = _streamParser.InputStream.AudioStream.StreamId;

            if (!changed)
            {
                return(NOERROR);
            }

            // Update output pin
            var audioPin = Pins.OfType <SplitterOutputPin>().FirstOrDefault(p => p.Track.Type == DemuxTrack.TrackType.Audio);

            if (audioPin != null)
            {
                AMMediaType mt;
                if (MediaTypeBuilder.TryGetType(_streamParser.InputStream.AudioStream, out mt))
                {
                    _streamParser.Tracks[1].SetStreamMediaType(mt);
                }
                var res = RenameOutputPin(audioPin, oldAudioStream, newAudioStream);
            }

            if (IsActive && dwFlags != AMStreamSelectEnableFlags.DisableAll)
            {
                try
                {
                    IMediaSeeking seeking = (IMediaSeeking)FilterGraph;
                    if (seeking != null)
                    {
                        long current;
                        seeking.GetCurrentPosition(out current);
                        // Only seek during playback, not on initial selection
                        if (current != 0)
                        {
                            current -= UNITS / 10;
                            seeking.SetPositions(current, AMSeekingSeekingFlags.AbsolutePositioning, null, AMSeekingSeekingFlags.NoPositioning);
                            current += UNITS / 10;
                            seeking.SetPositions(current, AMSeekingSeekingFlags.AbsolutePositioning, null, AMSeekingSeekingFlags.NoPositioning);
                        }
                    }
                }
                catch
                {
                }
            }
            return(NOERROR);
        }
Exemple #25
0
        /// <summary>Runs the graph</summary>
        /// <param name="graphBuilder">The graph to be run.</param>
        /// <param name="seekableFilter">The filter to use for computing percent complete. Must implement IMediaSeeking.</param>
        protected void RunGraph(IGraphBuilder graphBuilder, IBaseFilter seekableFilter)
        {
            // Get the necessary control and event interfaces
            IMediaControl mediaControl = (IMediaControl)graphBuilder;
            IMediaEvent   mediaEvent   = (IMediaEvent)graphBuilder;

            // Get the media seeking interface to use for computing status and progress updates
            IMediaSeeking mediaSeeking = seekableFilter as IMediaSeeking;

            if (!CanGetPositionAndDuration(mediaSeeking))
            {
                mediaSeeking = graphBuilder as IMediaSeeking;
                if (!CanGetPositionAndDuration(mediaSeeking))
                {
                    mediaSeeking = null;
                }
            }

            // Publish the graph to the running object table and to a temporary file for examination/debugging purposes
            //using (new GraphPublisher(graphBuilder, "C:\\vidtests\\grf\\" + Guid.NewGuid().ToString("N") + ".grf"))
            {
                // Run the graph
                int hr = 0;
                hr = mediaControl.Pause();
                hr = mediaControl.Run();
                DsError.ThrowExceptionForHR(hr);

                try
                {
                    ProgressChanged(new object(), new ProgressChangedEventArgs(0.0)); // initial progress update stating 0% done
                    bool done = false;
                    while (!CancellationPending && !done)                             // continue until we're done/cancelled
                    {
                        // Poll to see how we're doing
                        EventCode statusCode;

                        hr = mediaEvent.WaitForCompletion(200, out statusCode);
                        Console.Write(" <" + statusCode.ToString() + ">,");
                        switch (statusCode)
                        {
                        case EventCode.Complete:
                            done = true;
                            break;

                        case 0:
                            // Get an update on where we are with the conversion
                            if (mediaSeeking != null)
                            {
                                long curPos;
                                mediaSeeking.GetCurrentPosition(out curPos);
                                long length;
                                mediaSeeking.GetDuration(out length);
                                double progress = curPos * 100.0 / (double)length;
                                if (progress > 0)
                                {
                                    ProgressChanged(new object(), new ProgressChangedEventArgs(progress));
                                }
                            }
                            break;

                        default:
                            // Error, so throw exception
                            EventCode tryCode;
                            IntPtr    lp1, lp2;
                            hr = mediaEvent.GetEvent(out tryCode, out lp1, out lp2, 200);
                            DsError.ThrowExceptionForHR(hr);
                            throw new Exception(statusCode.ToString());
                        }
                    }
                    ProgressChanged(new object(), new ProgressChangedEventArgs(100)); // final progress update stating 100% done
                }
                finally
                {
                    // We're done converting, so stop the graph
                    FilterState graphState;
                    mediaControl.GetState(100, out graphState);
                    if (graphState == FilterState.Running)
                    {
                        mediaControl.Pause();
                    }
                    mediaControl.Stop();


                    // Return done
                    Completed(new object(), new EventArgs());
                }
            }
        }
Exemple #26
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.ToLowerInvariant() != ".ts" && ext.ToLowerInvariant() != ".mpg")
   {
     Log.Info("TSReader2MP4: wrong file format");
     return false;
   }
   try
   {
     graphBuilder = (IGraphBuilder)new FilterGraph();
     _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder);
     Log.Info("TSReader2MP4: add filesource");
     TsReader reader = new TsReader();
     tsreaderSource = (IBaseFilter)reader;
     IBaseFilter filter = (IBaseFilter)tsreaderSource;
     graphBuilder.AddFilter(filter, "TSReader Source");
     IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource;
     Log.Info("TSReader2MP4: load file:{0}", info.file);
     int hr = fileSource.Load(info.file, null);
     //add audio/video codecs
     string strVideoCodec = "";
     string strH264VideoCodec = "";
     string strAudioCodec = "";
     string strAACAudioCodec = "";
     using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
     {
       strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", "");
       strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", "");
       strAACAudioCodec = xmlreader.GetValueAsString("mytv", "aacaudiocodec", "");
       strH264VideoCodec = xmlreader.GetValueAsString("mytv", "h264videocodec", "");
     }
     //Find the type of decoder required for the output video & audio pins on TSReader.
     Log.Info("TSReader2MP4: find tsreader compatible audio/video decoders");
     IPin pinOut0, pinOut1;
     IPin pinIn0, pinIn1;
     pinOut0 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 0); //audio
     pinOut1 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 1); //video
     if (pinOut0 == null || pinOut1 == null)
     {
       Log.Error("TSReader2MP4: FAILED: unable to get output pins of tsreader");
       Cleanup();
       return false;
     }
     bool usingAAC = false;
     IEnumMediaTypes enumMediaTypes;
     hr = pinOut0.EnumMediaTypes(out enumMediaTypes);
     while (true)
     {
       AMMediaType[] mediaTypes = new AMMediaType[1];
       int typesFetched;
       hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched);
       if (hr != 0 || typesFetched == 0) break;
       if (mediaTypes[0].majorType == MediaType.Audio && mediaTypes[0].subType == MediaSubType.LATMAAC)
       {
         Log.Info("TSReader2MP4: found LATM AAC audio out pin on tsreader");
         usingAAC = true;
       }
     }
     bool usingH264 = false;
     hr = pinOut1.EnumMediaTypes(out enumMediaTypes);
     while (true)
     {
       AMMediaType[] mediaTypes = new AMMediaType[1];
       int typesFetched;
       hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched);
       if (hr != 0 || typesFetched == 0) break;
       if (mediaTypes[0].majorType == MediaType.Video && mediaTypes[0].subType == AVC1)
       {
         Log.Info("TSReader2MP4: found H.264 video out pin on tsreader");
         usingH264 = true;
       }
     }
     //Add the type of decoder required for the output video & audio pins on TSReader.
     Log.Info("TSReader2MP4: add audio/video decoders to graph");
     if (usingH264 == false)
     {
       Log.Info("TSReader2MP4: add mpeg2 video decoder:{0}", strVideoCodec);
       VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec);
       if (VideoCodec == null)
       {
         Log.Error("TSReader2MP4: unable to add mpeg2 video decoder");
         Cleanup();
         return false;
       }
     }
     else
     {
       Log.Info("TSReader2MP4: add h264 video codec:{0}", strH264VideoCodec);
       VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec);
       if (VideoCodec == null)
       {
         Log.Error("TSReader2MP4: FAILED:unable to add h264 video codec");
         Cleanup();
         return false;
       }
     }
     if (usingAAC == false)
     {
       Log.Info("TSReader2MP4: add mpeg2 audio codec:{0}", strAudioCodec);
       AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec);
       if (AudioCodec == null)
       {
         Log.Error("TSReader2MP4: FAILED:unable to add mpeg2 audio codec");
         Cleanup();
         return false;
       }
     }
     else
     {
       Log.Info("TSReader2MP4: add aac audio codec:{0}", strAACAudioCodec);
       AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec);
       if (AudioCodec == null)
       {
         Log.Error("TSReader2MP4: FAILED:unable to add aac audio codec");
         Cleanup();
         return false;
       }
     }
     Log.Info("TSReader2MP4: connect tsreader->audio/video decoders");
     //connect output #0 (audio) of tsreader->audio decoder input pin 0
     //connect output #1 (video) of tsreader->video decoder input pin 0
     pinIn0 = DsFindPin.ByDirection(AudioCodec, PinDirection.Input, 0); //audio
     pinIn1 = DsFindPin.ByDirection(VideoCodec, PinDirection.Input, 0); //video
     if (pinIn0 == null || pinIn1 == null)
     {
       Log.Error("TSReader2MP4: FAILED: unable to get pins of video/audio codecs");
       Cleanup();
       return false;
     }
     hr = graphBuilder.Connect(pinOut0, pinIn0);
     if (hr != 0)
     {
       Log.Error("TSReader2MP4: FAILED: unable to connect audio pins :0x{0:X}", hr);
       Cleanup();
       return false;
     }
     hr = graphBuilder.Connect(pinOut1, pinIn1);
     if (hr != 0)
     {
       Log.Error("TSReader2MP4: FAILED: unable to connect video pins :0x{0:X}", hr);
       Cleanup();
       return false;
     }
     //add encoders, muxer & filewriter
     if (!AddCodecs(graphBuilder, info)) return false;
     //setup graph controls
     mediaControl = graphBuilder as IMediaControl;
     mediaSeeking = tsreaderSource as IMediaSeeking;
     mediaEvt = graphBuilder as IMediaEventEx;
     mediaPos = graphBuilder as IMediaPosition;
     //get file duration
     Log.Info("TSReader2MP4: Get duration of recording");
     long lTime = 5 * 60 * 60;
     lTime *= 10000000;
     long pStop = 0;
     hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                    AMSeekingSeekingFlags.NoPositioning);
     if (hr == 0)
     {
       long lStreamPos;
       mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position
       m_dDuration = lStreamPos;
       lTime = 0;
       mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                 AMSeekingSeekingFlags.NoPositioning);
     }
     double duration = m_dDuration / 10000000d;
     Log.Info("TSReader2MP4: recording duration: {0}", MediaPortal.Util.Utils.SecondsToHMSString((int)duration));
     //run the graph to initialize the filters to be sure
     hr = mediaControl.Run();
     if (hr != 0)
     {
       Log.Error("TSReader2MP4: FAILED: unable to start graph :0x{0:X}", hr);
       Cleanup();
       return false;
     }
     int maxCount = 20;
     while (true)
     {
       long lCurrent;
       mediaSeeking.GetCurrentPosition(out lCurrent);
       double dpos = (double)lCurrent;
       dpos /= 10000000d;
       System.Threading.Thread.Sleep(100);
       if (dpos >= 2.0d) break;
       maxCount--;
       if (maxCount <= 0) break;
     }
     mediaControl.Stop();
     FilterState state;
     mediaControl.GetState(500, out state);
     GC.Collect();
     GC.Collect();
     GC.Collect();
     GC.WaitForPendingFinalizers();
     graphBuilder.RemoveFilter(mp4Muxer);
     graphBuilder.RemoveFilter(h264Encoder);
     graphBuilder.RemoveFilter(aacEncoder);
     graphBuilder.RemoveFilter((IBaseFilter)fileWriterFilter);
     if (!AddCodecs(graphBuilder, info)) return false;
     //Set Encoder quality & Muxer settings
     if (!EncoderSet(graphBuilder, info)) return false;
     //start transcoding - run the graph
     Log.Info("TSReader2MP4: start transcoding");
     //setup flow control
     //need to leverage CBAsePin, CPullPin & IAsyncReader methods.
     IAsyncReader synchVideo = null;
     mediaSample = VideoCodec as IMediaSample;
     hr = synchVideo.SyncReadAligned(mediaSample);
     //So we only parse decoder output whent the encoders are ready.
     hr = mediaControl.Run();
     if (hr != 0)
     {
       Log.Error("TSReader2MP4: FAILED:unable to start graph :0x{0:X}", hr);
       Cleanup();
       return false;
     }
   }
   catch (Exception ex)
   {
     Log.Error("TSReader2MP4: Unable create graph: {0}", ex.Message);
     Cleanup();
     return false;
   }
   return true;
 }
 public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard)
 {
   try
   {
     if (!Supports(format)) return false;
     string ext = System.IO.Path.GetExtension(info.file);
     if (ext.ToLower() != ".ts" && ext.ToLower() != ".mpg")
     {
       Log.Info("TSReader2WMV: wrong file format");
       return false;
     }
     Log.Info("TSReader2WMV: create graph");
     graphBuilder = (IGraphBuilder)new FilterGraph();
     _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder);
     Log.Info("TSReader2WMV: add filesource");
     TsReader reader = new TsReader();
     tsreaderSource = (IBaseFilter)reader;
     //ITSReader ireader = (ITSReader)reader;
     //ireader.SetTsReaderCallback(this);
     //ireader.SetRequestAudioChangeCallback(this);
     IBaseFilter filter = (IBaseFilter)tsreaderSource;
     graphBuilder.AddFilter(filter, "TSReader Source");
     IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource;
     Log.Info("TSReader2WMV: load file:{0}", info.file);
     int hr = fileSource.Load(info.file, null);
     //add audio/video codecs
     string strVideoCodec = "";
     string strH264VideoCodec = "";
     string strAudioCodec = "";
     string strAACAudioCodec = "";
     using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
     {
       strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", "");
       strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", "");
       strAACAudioCodec = xmlreader.GetValueAsString("mytv", "aacaudiocodec", "");
       strH264VideoCodec = xmlreader.GetValueAsString("mytv", "h264videocodec", "");
     }
     //Find the type of decoder required for the output video & audio pins on TSReader.
     Log.Info("TSReader2WMV: find tsreader compatible audio/video decoders");
     IPin pinOut0, pinOut1;
     IPin pinIn0, pinIn1;
     pinOut0 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 0); //audio
     pinOut1 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 1); //video
     if (pinOut0 == null || pinOut1 == null)
     {
       Log.Error("TSReader2WMV: FAILED: unable to get output pins of tsreader");
       Cleanup();
       return false;
     }
     bool usingAAC = false;
     IEnumMediaTypes enumMediaTypes;
     hr = pinOut0.EnumMediaTypes(out enumMediaTypes);
     while (true)
     {
       AMMediaType[] mediaTypes = new AMMediaType[1];
       int typesFetched;
       hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched);
       if (hr != 0 || typesFetched == 0) break;
       if (mediaTypes[0].majorType == MediaType.Audio && mediaTypes[0].subType == MediaSubType.LATMAAC)
       {
         Log.Info("TSReader2WMV: found LATM AAC audio out pin on tsreader");
         usingAAC = true;
       }
     }
     bool usingH264 = false;
     hr = pinOut1.EnumMediaTypes(out enumMediaTypes);
     while (true)
     {
       AMMediaType[] mediaTypes = new AMMediaType[1];
       int typesFetched;
       hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched);
       if (hr != 0 || typesFetched == 0) break;
       if (mediaTypes[0].majorType == MediaType.Video && mediaTypes[0].subType == AVC1)
       {
         Log.Info("TSReader2WMV: found H.264 video out pin on tsreader");
         usingH264 = true;
       }
     }
     //Add the type of decoder required for the output video & audio pins on TSReader.
     Log.Info("TSReader2WMV: add audio/video decoders to graph");
     if (usingH264 == false)
     {
       Log.Info("TSReader2WMV: add mpeg2 video decoder:{0}", strVideoCodec);
       VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec);
       if (VideoCodec == null)
       {
         Log.Error("TSReader2WMV: unable to add mpeg2 video decoder");
         Cleanup();
         return false;
       }
     }
     else
     {
       Log.Info("TSReader2WMV: add h264 video codec:{0}", strH264VideoCodec);
       VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec);
       if (VideoCodec == null)
       {
         Log.Error("TSReader2WMV: FAILED:unable to add h264 video codec");
         Cleanup();
         return false;
       }
     }
     if (usingAAC == false)
     {
       Log.Info("TSReader2WMV: add mpeg2 audio codec:{0}", strAudioCodec);
       AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec);
       if (AudioCodec == null)
       {
         Log.Error("TSReader2WMV: FAILED:unable to add mpeg2 audio codec");
         Cleanup();
         return false;
       }
     }
     else
     {
       Log.Info("TSReader2WMV: add aac audio codec:{0}", strAACAudioCodec);
       AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec);
       if (AudioCodec == null)
       {
         Log.Error("TSReader2WMV: FAILED:unable to add aac audio codec");
         Cleanup();
         return false;
       }
     }
     Log.Info("TSReader2WMV: connect tsreader->audio/video decoders");
     //connect output #0 (audio) of tsreader->audio decoder input pin 0
     //connect output #1 (video) of tsreader->video decoder input pin 0
     pinIn0 = DsFindPin.ByDirection(AudioCodec, PinDirection.Input, 0); //audio
     pinIn1 = DsFindPin.ByDirection(VideoCodec, PinDirection.Input, 0); //video
     if (pinIn0 == null || pinIn1 == null)
     {
       Log.Error("TSReader2WMV: FAILED: unable to get pins of video/audio codecs");
       Cleanup();
       return false;
     }
     hr = graphBuilder.Connect(pinOut0, pinIn0);
     if (hr != 0)
     {
       Log.Error("TSReader2WMV: FAILED: unable to connect audio pins :0x{0:X}", hr);
       Cleanup();
       return false;
     }
     hr = graphBuilder.Connect(pinOut1, pinIn1);
     if (hr != 0)
     {
       Log.Error("TSReader2WMV: FAILED: unable to connect video pins :0x{0:X}", hr);
       Cleanup();
       return false;
     }
     string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv");
     if (!AddWmAsfWriter(outputFilename, quality, standard)) return false;
     Log.Info("TSReader2WMV: start pre-run");
     mediaControl = graphBuilder as IMediaControl;
     mediaSeeking = tsreaderSource as IMediaSeeking;
     mediaEvt = graphBuilder as IMediaEventEx;
     mediaPos = graphBuilder as IMediaPosition;
     //get file duration
     long lTime = 5 * 60 * 60;
     lTime *= 10000000;
     long pStop = 0;
     hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                    AMSeekingSeekingFlags.NoPositioning);
     if (hr == 0)
     {
       long lStreamPos;
       mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position
       m_dDuration = lStreamPos;
       lTime = 0;
       mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                 AMSeekingSeekingFlags.NoPositioning);
     }
     double duration = m_dDuration / 10000000d;
     Log.Info("TSReader2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration));
     hr = mediaControl.Run();
     if (hr != 0)
     {
       Log.Error("TSReader2WMV: FAILED: unable to start graph :0x{0:X}", hr);
       Cleanup();
       return false;
     }
     int maxCount = 20;
     while (true)
     {
       long lCurrent;
       mediaSeeking.GetCurrentPosition(out lCurrent);
       double dpos = (double)lCurrent;
       dpos /= 10000000d;
       System.Threading.Thread.Sleep(100);
       if (dpos >= 2.0d) break;
       maxCount--;
       if (maxCount <= 0) break;
     }
     Log.Info("TSReader2WMV: pre-run done");
     Log.Info("TSReader2WMV: Get duration of movie");
     mediaControl.Stop();
     FilterState state;
     mediaControl.GetState(500, out state);
     GC.Collect();
     GC.Collect();
     GC.Collect();
     GC.WaitForPendingFinalizers();
     Log.Info("TSReader2WMV: reconnect mpeg2 video codec->ASF WM Writer");
     graphBuilder.RemoveFilter(fileWriterbase);
     if (!AddWmAsfWriter(outputFilename, quality, standard)) return false;
     Log.Info("TSReader2WMV: Start transcoding");
     hr = mediaControl.Run();
     if (hr != 0)
     {
       Log.Error("TSReader2WMV:FAILED:unable to start graph :0x{0:X}", hr);
       Cleanup();
       return false;
     }
   }
   catch (Exception e)
   {
     // TODO: Handle exceptions.
     Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message);
     return false;
   }
   return true;
 }
Exemple #28
0
        private static Bitmap GetBitmap(IGraphBuilder graph, ISampleGrabber sg, long grabPosition, out EventCode ec)
        {
            IntPtr pBuffer     = IntPtr.Zero;
            int    pBufferSize = 0;
            Bitmap b           = null;
            int    hr          = 0;

            try
            {
                IMediaSeeking ims = graph as IMediaSeeking;

                bool canDuration = false;
                bool canPos      = false;
                bool canSeek     = false;
                long pDuration   = 0;
                long pCurrent    = 0;

                if (ims != null)
                {
                    AMSeekingSeekingCapabilities caps;

                    hr = ims.GetCapabilities(out caps);
                    if ((caps & AMSeekingSeekingCapabilities.CanGetDuration) == AMSeekingSeekingCapabilities.CanGetDuration)
                    {
                        canDuration = true;
                    }
                    if ((caps & AMSeekingSeekingCapabilities.CanGetCurrentPos) == AMSeekingSeekingCapabilities.CanGetCurrentPos)
                    {
                        canPos = true;
                    }
                    if ((caps & AMSeekingSeekingCapabilities.CanSeekAbsolute) == AMSeekingSeekingCapabilities.CanSeekAbsolute)
                    {
                        canSeek = true;
                    }

                    if (canDuration)
                    {
                        hr = ims.GetDuration(out pDuration);
                    }

                    if (grabPosition > pDuration)
                    {
                        grabPosition = pDuration - 1;
                    }

                    if (canSeek)
                    {
                        hr = ims.SetPositions(new DsLong(grabPosition), AMSeekingSeekingFlags.AbsolutePositioning, 0, AMSeekingSeekingFlags.NoPositioning);
                        DsError.ThrowExceptionForHR(hr);
                    }

                    if (canPos)
                    {
                        hr = ims.GetCurrentPosition(out pCurrent);
                    }
                }

                if (canPos)
                {
                    hr = ims.GetCurrentPosition(out pCurrent);
                }

                IMediaControl mControl = graph as IMediaControl;
                IMediaEvent   mEvent   = graph as IMediaEvent;

                //ec = EventCode.SystemBase;

                hr = mControl.Pause();
                DsError.ThrowExceptionForHR(hr);

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

                hr = mEvent.WaitForCompletion(int.MaxValue, out ec);
                DsError.ThrowExceptionForHR(hr);

                hr = mControl.Pause();
                DsError.ThrowExceptionForHR(hr);

                hr = mControl.Stop();
                DsError.ThrowExceptionForHR(hr);

                if (ec != EventCode.Complete)
                {
                    return(null);
                }

                hr = sg.GetCurrentBuffer(ref pBufferSize, pBuffer);
                DsError.ThrowExceptionForHR(hr);

                pBuffer = Marshal.AllocCoTaskMem(pBufferSize);

                hr = sg.GetCurrentBuffer(ref pBufferSize, pBuffer);
                DsError.ThrowExceptionForHR(hr);

                if (pBuffer != IntPtr.Zero)
                {
                    AMMediaType sgMt        = new AMMediaType();
                    int         videoWidth  = 0;
                    int         videoHeight = 0;
                    int         stride      = 0;

                    try
                    {
                        hr = sg.GetConnectedMediaType(sgMt);
                        DsError.ThrowExceptionForHR(hr);

                        if (sgMt.formatPtr != IntPtr.Zero)
                        {
                            if (sgMt.formatType == FormatType.VideoInfo)
                            {
                                VideoInfoHeader vih = (VideoInfoHeader)Marshal.PtrToStructure(sgMt.formatPtr, typeof(VideoInfoHeader));
                                videoWidth  = vih.BmiHeader.Width;
                                videoHeight = vih.BmiHeader.Height;
                                stride      = videoWidth * (vih.BmiHeader.BitCount / 8);
                            }
                            else
                            {
                                throw new ApplicationException("Unsupported Sample");
                            }

                            b = new Bitmap(videoWidth, videoHeight, stride, System.Drawing.Imaging.PixelFormat.Format32bppRgb, pBuffer);
                            b.RotateFlip(RotateFlipType.RotateNoneFlipY);
                        }
                    }
                    finally
                    {
                        DsUtils.FreeAMMediaType(sgMt);
                    }
                }

                return(b);
            }
            finally
            {
                if (pBuffer != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pBuffer);
                }
            }
        }
        private bool CheckGraphConversion(ref IMediaSeeking mediaSeeking)
        {
            int hr;
            IMediaEvent mediaEvent = (IMediaEvent)currentFilterGraph;

            // Check the graph / conversion is going ok, and raise any progress events
            EventCode statusCode;
            hr = mediaEvent.WaitForCompletion(100, out statusCode);
            switch (statusCode)
            {
                case EventCode.Complete:
                    return true;
                case 0:  // Still going - fire event with an update on where we are
                    if (mediaSeeking != null)
                    {
                        long curPos;
                        mediaSeeking.GetCurrentPosition(out curPos);
                        long length;
                        mediaSeeking.GetDuration(out length);
                        double progress = curPos * 100.0 / (double)length;
                        if (ConversionProgressChanged != null)
                            ConversionProgressChanged(new object(), new ProgressChangedEventArgs(progress));
                    }
                    return false;
                default:  // Error
                    EventCode tryCode;
                    IntPtr lp1, lp2;
                    hr = mediaEvent.GetEvent(out tryCode, out lp1, out lp2, 200);
                    DsError.ThrowExceptionForHR(hr);
                    throw new Exception(statusCode.ToString());
            }
        }