Example #1
0
            public Int32 SampleCB(Double SampleTime, IMediaSample pSample)
            {
                if (pSample == null)
                {
                    return(-1);
                }
                var    len = pSample.GetActualDataLength( );
                IntPtr pbuf;

                if (pSample.GetPointer(out pbuf) == 0 && len > 0)
                {
                    var buf = new Byte [len];
                    Marshal.Copy(pbuf, buf, 0, len);
                    var image = new Bitmap(640, 480);
                    var at    = 0;
                    if (len % 3 != 0)
                    {
                        // image is not bitmap 24bit, what now, burn it to the ground?
                        return(0);
                    }
                    for (var bOff = 0; bOff < len; bOff += 3)
                    {
                        var color = Color.FromArgb(buf [bOff + 2], buf [bOff + 1], buf [bOff]);
                        var x     = (image.Width - 1) - (at % image.Width);
                        var y     = (image.Height - 1) - (at / image.Width % image.Height);
                        image.SetPixel(x, y, color);
                        at++;
                    }
                    lastImage?.Dispose( );
                    lastImage = image;
                }
                Marshal.ReleaseComObject(pSample);
                return(0);
            }
Example #2
0
        /// <summary>
        /// Sample callback, NOT USED.
        /// </summary>
        /// <param name="SampleTime">The sample time.</param>
        /// <param name="pSample">The media sample.</param>
        /// <returns>The result.</returns>
        int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
        {
            if (!_gotOneImage)
            {
                // Set bGotOne to prevent further calls until we
                // request a new bitmap.
                _gotOneImage = true;
                IntPtr pBuffer;

                pSample.GetPointer(out pBuffer);
                int iBufferLen = pSample.GetSize();

                if (pSample.GetSize() > _strideImage * _videoHeightImage)
                {
                    throw new Exception("Buffer is wrong size");
                }

                Devices.CopyMemory(_handleImage, pBuffer, _strideImage * _videoHeightImage);

                // Picture is ready.
                if (_pictureReadyImage != null)
                {
                    _pictureReadyImage.Set();
                }
            }

            Marshal.ReleaseComObject(pSample);
            return(0);
        }
Example #3
0
        /// <summary> sample callback, NOT USED. </summary>
        int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
        {
            if (!m_bGotOne)
            {
                // Set bGotOne to prevent further calls until we
                // request a new bitmap.
                m_bGotOne = true;
                IntPtr pBuffer;

                pSample.GetPointer(out pBuffer);
                int iBufferLen = pSample.GetSize();

                if (iBufferLen > m_stride * m_videoHeight)
                {
                    throw new Exception("Buffer is wrong size");
                }

#if !LIB
                unsafe
                {
                    Buffer.MemoryCopy(pBuffer.ToPointer(), m_handle.ToPointer(), iBufferLen, iBufferLen);
                }
#endif
                // Picture is ready.
                m_PictureReady.Set();
            }

            Marshal.ReleaseComObject(pSample);
            return(0);
        }
Example #4
0
        private bool ProcessInternal <T>(IAudioDescription input, IntPtr samples, short channels, int length, IMediaSample output) where T : struct
        {
            UpdateGpuResources(length);

            var sampleCount = length / channels;

            try
            {
                var devInputSamples = GetDevInputSamples <T>(length);
                var devInputResult  = GetDevNormSamples(channels, sampleCount);
                var devOutputResult = GetDevOutputSamples <T>(length);
                Gpu.CopyToDevice(samples, 0, devInputSamples, 0, length);
                Gpu.Launch(AudioProc.THREAD_COUNT, 1, string.Format("GetSamples{0}", typeof(T).Name),
                           devInputSamples, devInputResult);
                Process(input, devInputResult, channels, sampleCount);
                output.GetPointer(out samples);
                Gpu.Launch(AudioProc.THREAD_COUNT, 1, string.Format("PutSamples{0}", typeof(T).Name),
                           devInputResult, devOutputResult);
                Gpu.CopyFromDevice(devOutputResult, 0, samples, 0, length);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                return(false);
            }
            return(true);
        }
        int ISampleGrabberCB.SampleCB(double sampleTime, IMediaSample pSample)
        {
            try
            {
                if (transcoderError != null)
                {
                    return(WinAPI.E_FAIL);
                }

                samplesProcessed += 1;

                int    dataLen = pSample.GetActualDataLength();
                IntPtr bufPtr;
                int    hr = pSample.GetPointer(out bufPtr);

                bool processed = ProcessSample(bufPtr, dataLen, sampleTime);

                return(processed ? WinAPI.S_OK : WinAPI.E_FAIL);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
            finally
            {
                Marshal.ReleaseComObject(pSample);
            }

            return(WinAPI.E_FAIL);
        } // end of SampleCB
Example #6
0
        /// <summary>
        /// Sample callback, NOT USED.
        /// </summary>
        /// <param name="SampleTime">The sample time.</param>
        /// <param name="pSample">The media sample.</param>
        /// <returns>The result.</returns>
        int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
        {
            if (!_gotOneSound)
            {
                // Set bGotOne to prevent further calls until we
                // request a new bitmap.
                _gotOneSound = true;
                IntPtr pBuffer;

                pSample.GetPointer(out pBuffer);
                int iBufferLen = pSample.GetSize();

                if (pSample.GetSize() > _soundMemorySize)
                {
                    throw new Exception("Buffer is wrong size");
                }

                Directx.Utility.Devices.CopyMemory(_handleSound, pBuffer, _soundMemorySize);

                // Picture is ready.
                if (_audoReadySound != null)
                {
                    _audoReadySound.Set();
                }
            }

            Marshal.ReleaseComObject(pSample);
            return(0);
        }
        /// <summary> sample callback, NOT USED. </summary>
        int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
        {
            if (!m_bGotOne)
            {
                // Set bGotOne to prevent further calls until we
                // request a new bitmap.
                m_bGotOne = true;
                IntPtr pBuffer;

                pSample.GetPointer(out pBuffer);
                int iBufferLen = pSample.GetSize();

                if (pSample.GetSize() > m_stride * m_videoHeight)
                {
                    throw new Exception("Buffer is wrong size");
                }

                NativeMethods.CopyMemory(m_handle, pBuffer, m_stride * m_videoHeight);

                // Picture is ready.
                m_PictureReady.Set();
            }

            Marshal.ReleaseComObject(pSample);
            return(0);
        }
Example #8
0
            public int SampleCB(double SampleTime, IMediaSample pSample)
            {
                if (pSample == null)
                {
                    return(-1);
                }

                if (Trigger.WaitOne(0))
                {
                    int len = pSample.GetActualDataLength();
                    if (len > 0)
                    {
                        IntPtr buf;
                        if (pSample.GetPointer(out buf) == 0)
                        {
                            byte[] buffer = new byte[len];
                            Marshal.Copy(buf, buffer, 0, len);

                            using (var bmp = new Bitmap(Width, Height, Stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, buf))
                            {
                                bmp.RotateFlip(RotateFlipType.Rotate180FlipX);
                                _previewImage = (Bitmap)bmp.Clone();
                                callback?.Invoke();
                                //using (var ms = new MemoryStream())
                                //{
                                //    //bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                                //    bmp.Save("hallo.pnb");
                                //    //byte[] data = ms.ToArray();

                                //    //var uri = new Uri($"");
                                //    //var req = (HttpWebRequest)HttpWebRequest.Create(uri);
                                //    //req.Method = "POST";
                                //    //req.ContentType = "application/octet-stream";
                                //    //req.Headers.Add("Ocp-Apim-Subscription-Key", "");
                                //    //req.ContentLength = data.Length;
                                //    //using (var stm = req.GetRequestStream())
                                //    //    stm.Write(data, 0, data.Length);
                                //    //using (var res = req.GetResponse())
                                //    //using (var stm = res.GetResponseStream())
                                //    //using (var sr = new StreamReader(stm))
                                //    //using (var jr = new JsonTextReader(sr))
                                //    //{
                                //    //    var obj = serializer.Deserialize<ExpandoObject[]>(jr);

                                //    //}
                                //}
                            }
                        }
                    }
                    Trigger.Reset();
                }

                Marshal.ReleaseComObject(pSample);

                return(0);
            }
Example #9
0
        int ISampleGrabberCB.SampleCB(double sampleTime, IMediaSample pSample)
        {
            var mediaType = new AMMediaType();

            /* We query for the media type the sample grabber is using */
            int hr = m_sampleGrabber.GetConnectedMediaType(mediaType);

            var videoInfo = new VideoInfoHeader();

            /* 'Cast' the pointer to our managed struct */
            Marshal.PtrToStructure(mediaType.formatPtr, videoInfo);

            /* The stride is "How many bytes across for each pixel line (0 to width)" */
            int stride = Math.Abs(videoInfo.BmiHeader.Width * (videoInfo.BmiHeader.BitCount / 8 /* eight bits per byte */));
            int width  = videoInfo.BmiHeader.Width;
            int height = videoInfo.BmiHeader.Height;

            if (m_videoFrame == null)
            {
                InitializeBitmapFrame(width, height);
            }

            if (m_videoFrame == null)
            {
                return(0);
            }

            BitmapData bmpData = m_videoFrame.LockBits(new Rectangle(0, 0, width, height),
                                                       ImageLockMode.ReadWrite,
                                                       PixelFormat.Format24bppRgb);

            /* Get the pointer to the pixels */
            IntPtr pBmp = bmpData.Scan0;

            IntPtr samplePtr;

            /* Get the native pointer to the sample */
            pSample.GetPointer(out samplePtr);

            int pSize = stride * height;

            /* Copy the memory from the sample pointer to our bitmap pixel pointer */
            CopyMemory(pBmp, samplePtr, pSize);

            m_videoFrame.UnlockBits(bmpData);

            InvokeNewVideoSample(new VideoSampleArgs {
                VideoFrame = m_videoFrame
            });

            DsUtils.FreeAMMediaType(mediaType);

            /* Dereference the sample COM object */
            Marshal.ReleaseComObject(pSample);
            return(0);
        }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="SampleTime"></param>
        /// <param name="pSample"></param>
        /// <returns></returns>
        public int SampleCB(double SampleTime, IMediaSample pSample)
        {
            IntPtr pBuffer;

            pSample.GetPointer(out pBuffer);
            int BufferLen = pSample.GetActualDataLength();

            Marshal.ReleaseComObject(pSample);
            return(0);
        }
Example #11
0
		/// <summary>
		/// コンストラクタ (初期値指定)
		/// </summary>
		/// <param name="sample_time">サンプルタイム</param>
		/// <param name="sample_data">サンプルデータ</param>
		public CxSampleGrabberEventArgs(double sample_time, IMediaSample sample_data)
		{
			SampleTime = sample_time;
			SampleData = sample_data;
			if (sample_data != null)
			{
				sample_data.GetPointer(ref m_Address);
				m_Length = sample_data.GetSize();
			}
		}
Example #12
0
        void TestPointer()
        {
            int    hr;
            IntPtr ppBuffer;

            // No particular test, just see if it will read.
            hr = m_ims.GetPointer(out ppBuffer);
            Marshal.ThrowExceptionForHR(hr);

            Debug.Assert(ppBuffer != IntPtr.Zero, "GetPointer");
        }
        public int SampleCB(double sampleTime, IMediaSample pSample)
        {
            IntPtr ptr;

            pSample.GetPointer(out ptr);

            Execute(ptr, VideoHeight, VideoStride);

            Marshal.ReleaseComObject(pSample);
            return(0);
        }
Example #14
0
     public int SampleCB(double SampleTime, IMediaSample pSample)
     {
         if (pSample == null) return -1;
         int len = pSample.GetActualDataLength();
         IntPtr pBuf;
         if (pSample.GetPointer(out pBuf) == 0 && len > 0)
         { 
             m_imageBuf = null;
             m_imageBuf = new byte[len];
             Marshal.Copy(pBuf, m_imageBuf, 0, len);
         }
         return 0;
 }
Example #15
0
        /// <summary>
        /// The callback from the GSSF to populate the sample.  This class isn't intended
        /// to be overridden.  Child classes should instead implement PopulateSample,
        /// which this method calls.
        /// </summary>
        /// <param name="pSample">The sample to populate</param>
        /// <returns>HRESULT</returns>
        public int SampleCallback(IMediaSample pSample)
        {
            int    hr;
            IntPtr pData;

            try
            {
                // Get the buffer into which we will copy the data
                hr = pSample.GetPointer(out pData);
                if (hr >= 0)
                {
                    // Find out the amount of space in the buffer
                    int cbData = pSample.GetSize();

                    lock (this)
                    {
                        hr = SetTimeStamps(pSample);
                        if (hr >= 0)
                        {
                            int iRead;

                            // Populate the sample
                            hr = PopulateSample(pData, cbData, out iRead);
                            if (hr >= 0)
                            {
                                if (hr == S_Ok) // 1 == End of stream
                                {
                                    // increment the frame number for next time
                                    m_iFrameNumber++;
                                }
                                else
                                {
                                    m_iFrameNumber = 0;
                                }

                                pSample.SetActualDataLength(iRead);
                            }
                        }
                    }
                }
            }
            finally
            {
                // Release our pointer the the media sample.  THIS IS ESSENTIAL!  If
                // you don't do this, the graph will stop after about 2 samples.
                Marshal.ReleaseComObject(pSample);
            }

            return(hr);
        }
Example #16
0
        public int SampleCB(double SampleTime, IMediaSample pSample)
        {
            DateTime dt = DateTime.Now;

            lock (this)
            {
                sb.AppendFormat("{0:T}.{1:D3}: ", dt, dt.Millisecond);
                sb.AppendFormat("SampleTime={0:G4}, ", SampleTime);
                if (pSample != null)
                {
                    long start = 0, end = 0;
                    pSample.GetTime(out start, out end);
                    sb.AppendFormat("Time(start={0}, end={1}), ", start, end);
                    pSample.GetMediaTime(out start, out end);
                    sb.AppendFormat("MediaTime(start={0}, end={1}), ", start, end);
                    int len = pSample.GetActualDataLength();
                    sb.AppendFormat("data length={0}, ", len);
                    bool syncpoint = pSample.IsSyncPoint() == 0;
                    sb.AppendFormat("keyframe={0}", syncpoint);
                    if (pSample.IsDiscontinuity() == 0)
                    {
                        sb.Append(", Discontinuity");
                    }
                    if (pSample.IsPreroll() == 0)
                    {
                        sb.Append(", Preroll");
                    }
                    int    n = Math.Min(len, 8);
                    IntPtr pbuf;
                    if (pSample.GetPointer(out pbuf) == 0)
                    {
                        byte[] buf = new byte[n];
                        Marshal.Copy(pbuf, buf, 0, n);
                        sb.Append(", Data=");
                        for (int i = 0; i < n; i++)
                        {
                            sb.AppendFormat("{0:X2}", buf[i]);
                        }
                        sb.Append("...");
                    }
                }
                else
                {
                    sb.Append("pSample==NULL!");
                }
                sb.Append(Environment.NewLine);
            }
            Marshal.ReleaseComObject(pSample);
            return(0);
        }
 public int SampleCB(double SampleTime, IMediaSample pSample)
 {
     //  Console.WriteLine("**********************55555555555555555555555**********************");
     if (pSample == null) return -1;
     int len = pSample.GetActualDataLength();
     IntPtr pbuf;
     if (pSample.GetPointer(out pbuf) == 0 && len > 0)
     {
         byte[] buf = new byte[len];
         Marshal.Copy(pbuf, buf, 0, len);
         for (int i = 0; i < len; i += 2)
             buf[i] = (byte)(255 - buf[i]);
         Marshal.Copy(buf, 0, pbuf, len);
     }
     return 0;
 }
Example #18
0
        /// <summary>
        /// Called by the GenericSampleSourceFilter.  This routine populates the MediaSample.
        /// </summary>
        /// <param name="sample">Pointer to a sample</param>
        /// <returns>0 = success, 1 = end of stream, negative values for errors</returns>
        public virtual int SampleCallback(IMediaSample sample)
        {
            int    hr;
            IntPtr dataPointer;

            try
            {
                // Get the buffer into which we will copy the data
                hr = sample.GetPointer(out dataPointer);
                if (hr >= 0)
                {
                    // Set TRUE on every sample for uncompressed frames
                    hr = sample.SetSyncPoint(true);
                    if (hr >= 0)
                    {
                        // Find out the amount of space in the buffer
                        int callbackData = sample.GetSize();

                        hr = this.SetTimeStamps(sample);
                        if (hr >= 0)
                        {
                            int read;

                            // Get copy the data into the sample
                            hr = this.GetImage(this.frameNumber, dataPointer, callbackData, out read);

                            // 1 == End of stream
                            if (hr == 0)
                            {
                                sample.SetActualDataLength(read);

                                // increment the frame number for next time
                                this.frameNumber++;
                            }
                        }
                    }
                }
            }
            finally
            {
                // Release our pointer the the media sample.  THIS IS ESSENTIAL!  If
                // you don't do this, the graph will stop after about 2 samples.
                Marshal.ReleaseComObject(sample);
            }

            return(hr);
        }
Example #19
0
        private int PopulateMediaSample(IMediaSample pSample)
        {
            int  hr;
            long tStart, tStop;

            // Read the file offsets they are seeking
            hr = pSample.GetTime(out tStart, out tStop);
            if (hr >= 0)
            {
                IntPtr pBuffer = IntPtr.Zero;

                // Turn the sample time into a file position and length
                long llPos       = tStart / UNIT;
                int  lLength     = (int)((tStop - tStart) / UNIT);
                int  iBufferSize = pSample.GetSize();

                Debug.Write(string.Format(" pos: {0} len: {1} size: {2}", llPos, lLength, iBufferSize));

                // Make sure the buffer they passed it big enough to hold
                // all the data they requested
                if (iBufferSize >= lLength)
                {
                    // This is where we store the data
                    hr = pSample.GetPointer(out pBuffer);
                }
                else
                {
                    hr = E_BufferTooSmall;
                }

                if (hr >= 0)
                {
                    int iBytesRead;

                    // Read the data into the buffer
                    hr = SyncReadInternal(llPos, lLength, pBuffer, out iBytesRead);
                    if (hr >= 0)
                    {
                        // How much of the buffer we used.
                        pSample.SetActualDataLength(iBytesRead);
                        Debug.Write(string.Format(" read: {0}", iBytesRead));
                    }
                }
            }

            return(hr);
        }
Example #20
0
        public static void CopySample(IMediaSample src, IMediaSample dest, bool copySamples)
        {
            var sourceSize = src.GetActualDataLength();

            if (copySamples)
            {
                IntPtr sourceBuffer;
                src.GetPointer(out sourceBuffer);

                IntPtr destBuffer;
                dest.GetPointer(out destBuffer);

                CopyMemory(destBuffer, sourceBuffer, sourceSize);
            }

            // Copy the sample times
            long start, end;

            if (src.GetTime(out start, out end) == S_OK)
            {
                dest.SetTime(start, end);
            }

            if (src.GetMediaTime(out start, out end) == S_OK)
            {
                dest.SetMediaTime(start, end);
            }

            // Copy the media type
            AMMediaType mediaType;
            var         changed = src.GetMediaType(out mediaType) == 0;

            if (changed)
            {
                dest.SetMediaType(mediaType);
                DsUtils.FreeAMMediaType(mediaType);
            }

            dest.SetSyncPoint(src.IsSyncPoint() == S_OK);
            dest.SetPreroll(src.IsPreroll() == S_OK);
            dest.SetDiscontinuity(src.IsDiscontinuity() == S_OK);

            // Copy the actual data length
            dest.SetActualDataLength(sourceSize);
        }
Example #21
0
        private bool ProcessCpuInternal <T>(IAudioDescription input, IntPtr samples, short channels, int length, IMediaSample output) where T : struct
        {
            UpdateGpuResources(length);

            var inputSamples = GetInputSamplesCpu <T>(samples, channels, length);

            if (inputSamples == null)
            {
                return(false);
            }

            var sampleCount = length / channels;

            Process(input, inputSamples, channels, sampleCount);

            output.GetPointer(out samples);
            return(PutOutputSamplesCpu <T>(inputSamples, samples));
        }
        int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
        {
            int result = 0;

            if (_fSampleCB != null)
            {
                _fSampleCB(SampleTime, pSample);
            }

            IntPtr pBuff = IntPtr.Zero;
            var    size  = pSample.GetActualDataLength();

            pSample.GetPointer(out pBuff);
            if (_fBufferCB != null)
            {
                _fBufferCB(SampleTime, pBuff, size);
            }

            Marshal.FinalReleaseComObject(pSample);
            return(result);
        }
Example #23
0
        /// <summary>
        /// This routine populates the MediaSample.
        /// </summary>
        /// <param name="pSample">Pointer to a sample</param>
        /// <returns>0 = success, 1 = end of stream, negative values for errors</returns>
        public int MediaSampleCB(IMediaSample pSample)
        {
            int hr;

            try
            {
                IntPtr pData;

                hr = pSample.GetPointer(out pData);
                if (hr >= 0)
                {
                    hr = pSample.SetSyncPoint(true);
                    if (hr >= 0)
                    {
                        var len = Source.Read(pData, Constants.DShowNumberOfPacketsTS);
                        if (len != 0)
                        {
                            hr = 0;
                            pSample.SetActualDataLength(len);
                        }
                        else
                        {
                            //hr = 1;
                            hr = 0;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.ErrorException("Error in Sample handler.", ex);
                hr = -1;
            }
            finally
            {
                Marshal.ReleaseComObject(pSample);
            }

            return(hr);
        }
        public int SampleCB(double sampleTime, IMediaSample pSample)
        {
            try
            {
                if (!bProcess)
                {
                    return(WinAPI.E_FAIL);
                }

                // internal stats
                ++sampleIndex;
                long tStart, tEnd;

                pSample.GetMediaTime(out tStart, out tEnd);
                Debug.Assert(tStart < tEnd);
                Debug.Assert(tStart > lastMediaTime);
                sampleProcessed += tEnd - tStart;
                sampleDropped   += tStart - lastMediaTime - 1;
                lastMediaTime    = tEnd - 1;

                int    dataLen = pSample.GetActualDataLength();
                IntPtr bufPtr;
                int    hr = pSample.GetPointer(out bufPtr);
                Debug.Assert(0 == hr);

                bool processed = ProcessSample(bufPtr, dataLen, sampleTime);

                return(processed ? WinAPI.S_OK : WinAPI.E_FAIL);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
            finally
            {
                Marshal.ReleaseComObject(pSample);
            }

            return(WinAPI.E_FAIL);
        } // end of SampleCB
Example #25
0
        /// <summary> sample callback, NOT USED. </summary>
        int ISampleGrabberCB.SampleCB(double sampleTime, IMediaSample sample)
        {
            if (!hasPicture)
            {
                hasPicture = true;
                IntPtr bufferPointer;

                sample.GetPointer(out bufferPointer);
                int iBufferLen = sample.GetSize();
                if (sample.GetSize() > Stride * Height)
                {
                    throw new Exception("Buffer is wrong size");
                }

                CopyMemory(imageHandle, bufferPointer, Stride * Height);

                pictureReady.Set();
            }

            Marshal.ReleaseComObject(sample);
            return(0);
        }
Example #26
0
        public int SampleCB(double SampleTime, IMediaSample pSample)
        {
            //  Console.WriteLine("**********************55555555555555555555555**********************");
            if (pSample == null)
            {
                return(-1);
            }
            int    len = pSample.GetActualDataLength();
            IntPtr pbuf;

            if (pSample.GetPointer(out pbuf) == 0 && len > 0)
            {
                byte[] buf = new byte[len];
                Marshal.Copy(pbuf, buf, 0, len);
                for (int i = 0; i < len; i += 2)
                {
                    buf[i] = (byte)(255 - buf[i]);
                }
                Marshal.Copy(buf, 0, pbuf, len);
            }
            return(0);
        }
        public int SampleCB(double SampleTime, IMediaSample pSample)
        {
            if (!bProcess)
            {
                lastSampleTime = SampleTime;
                return(WinAPI.E_FAIL);
            }

            // internal stats
            ++sampleIndex;
            long tStart, tEnd;

            pSample.GetMediaTime(out tStart, out tEnd);
            Debug.Assert(tStart < tEnd);
            Debug.Assert(tStart > lastMediaTime);
            sampleProcessed += tEnd - tStart;
            sampleDropped   += tStart - lastMediaTime - 1;
            lastMediaTime    = tEnd - 1;

            int    dataLen = pSample.GetActualDataLength();
            IntPtr bufPtr;
            int    hr = pSample.GetPointer(out bufPtr);

            Debug.Assert(0 == hr);

            // BEGIN TRACE

            int bufSize = pSample.GetSize();

            long timeStart, timeEnd;

            pSample.GetTime(out timeStart, out timeEnd);

            string msg = string.Format(
                "SampleCB ({0}) {1}, sampleTime:{2} datalen:{3} bufsize:{4} mediaTime:{5}-{6} time:{7}-{8}",
                name, sampleIndex, SampleTime, dataLen, bufSize, tStart, tEnd, timeStart, timeEnd);

            Trace.WriteLine(msg);

            if (tStart - lastMediaTime - 1 > 0)
            {
                msg = string.Format("!!! Frame drop: {0}", tStart - lastMediaTime - 1 > 0);
                Trace.WriteLine(msg);
            }

            //END TRACE

            byte[] buf = new byte[dataLen];
            Marshal.Copy(bufPtr, buf, 0, dataLen);

            if (file != null)
            {
                file.Write(buf, 0, dataLen);
            }

            //DBG - simulate encoding error
            //if (sampleIndex > 100)
            //    goto STOP_CAPTURE;

            if (mediaState != null && mediaState.mpeg2Enc != null)
            {
                PrimoSoftware.AVBlocks.Transcoder enc = mediaState.mpeg2Enc;
                MediaSample inputSample = new MediaSample();
                inputSample.Buffer    = new MediaBuffer(buf);
                inputSample.StartTime = Math.Max(SampleTime, 0);
                //TODO: end time

                try
                {
                    bool pushed = false;

                    // transcoder.Push() is not threads safe.
                    // lock (enc){ } ensure that only one thread is calling transcoder.Push()
                    lock (enc)
                    {
                        pushed = enc.Push(StreamNumber, inputSample);
                    }

                    if (pushed)
                    {
                        return(0);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex.ToString());
                }

                Trace.WriteLine("PushSample FAILED");
            }

            //STOP_CAPTURE:

            Trace.WriteLine("SampleCB: Before Post STOP_CAPTURE");
            WinAPI.PostMessage(MainWindow, Util.WM_STOP_CAPTURE, new IntPtr(streamNumber), IntPtr.Zero);
            Trace.WriteLine("SampleCB: After Post STOP_CAPTURE");
            bProcess = false;
            return(WinAPI.E_FAIL);
        } // end of SampleCB
        int ISampleGrabberCB.SampleCB(double sampleTime, IMediaSample pSample)
        {
            var mediaType = new AMMediaType();

            /* We query for the media type the sample grabber is using */
            int hr = m_sampleGrabber.GetConnectedMediaType(mediaType);

            var videoInfo = new VideoInfoHeader();

            /* 'Cast' the pointer to our managed struct */
            Marshal.PtrToStructure(mediaType.formatPtr, videoInfo);

            /* The stride is "How many bytes across for each pixel line (0 to width)" */
            int stride = Math.Abs(videoInfo.BmiHeader.Width * (videoInfo.BmiHeader.BitCount / 8 /* eight bits per byte */));
            int width = videoInfo.BmiHeader.Width;
            int height = videoInfo.BmiHeader.Height;

            if (m_videoFrame == null)
                InitializeBitmapFrame(width, height);

            if (m_videoFrame == null)
                return 0;

            BitmapData bmpData = m_videoFrame.LockBits(new Rectangle(0, 0, width, height),
                                                       ImageLockMode.ReadWrite,
                                                       PixelFormat.Format24bppRgb);

            /* Get the pointer to the pixels */
            IntPtr pBmp = bmpData.Scan0;

            IntPtr samplePtr;

            /* Get the native pointer to the sample */
            pSample.GetPointer(out samplePtr);

            int pSize = stride * height;

            /* Copy the memory from the sample pointer to our bitmap pixel pointer */
            CopyMemory(pBmp, samplePtr, pSize);

            m_videoFrame.UnlockBits(bmpData);

            InvokeNewVideoSample(new VideoSampleArgs { VideoFrame = m_videoFrame });

            DsUtils.FreeAMMediaType(mediaType);

            /* Dereference the sample COM object */
            Marshal.ReleaseComObject(pSample);
            return 0;
        }
Example #29
0
        public static void CopySample(IMediaSample src, IMediaSample dest, bool copySamples)
        {
            var sourceSize = src.GetActualDataLength();

            if (copySamples)
            {
                IntPtr sourceBuffer;
                src.GetPointer(out sourceBuffer);

                IntPtr destBuffer;
                dest.GetPointer(out destBuffer);

                CopyMemory(destBuffer, sourceBuffer, sourceSize);
            }

            // Copy the sample times
            long start, end;

            if (src.GetTime(out start, out end) == S_OK)
            {
                dest.SetTime(start, end);
            }

            if (src.GetMediaTime(out start, out end) == S_OK)
            {
                dest.SetMediaTime(start, end);
            }

            // Copy the media type
            AMMediaType mediaType;
            src.GetMediaType(out mediaType);
            dest.SetMediaType(mediaType);
            DsUtils.FreeAMMediaType(mediaType);

            dest.SetSyncPoint(src.IsSyncPoint() == S_OK);
            dest.SetPreroll(src.IsPreroll() == S_OK);
            dest.SetDiscontinuity(src.IsDiscontinuity() == S_OK);

            // Copy the actual data length
            dest.SetActualDataLength(sourceSize);
        }
Example #30
0
 /// <summary>
 /// �R���X�g���N�^ (�����l�w��)
 /// </summary>
 /// <param name="sample_time">�T���v���^�C��</param>
 /// <param name="sample_data">�T���v���f�[�^</param>
 public CxSampleGrabberEventArgs(double sample_time, IMediaSample sample_data)
 {
     SampleTime = sample_time;
     SampleData = sample_data;
     if (sample_data != null)
     {
         sample_data.GetPointer(ref m_Address);
         m_Length = sample_data.GetSize();
     }
 }
Example #31
0
        /// <summary>
        /// The callback from the GSSF to populate the sample.  This class isn't intended
        /// to be overridden.  Child classes should instead implement PopulateSample,
        /// which this method calls.
        /// </summary>
        /// <param name="pSample">The sample to populate</param>
        /// <returns>HRESULT</returns>
        public int SampleCallback(IMediaSample pSample)
        {
            int hr;
            IntPtr pData;

            try
            {
                // Get the buffer into which we will copy the data
                hr = pSample.GetPointer(out pData);
                if (hr >= 0)
                {
                    // Find out the amount of space in the buffer
                    int cbData = pSample.GetSize();

                    lock (this)
                    {
                        hr = SetTimeStamps(pSample);
                        if (hr >= 0)
                        {
                            int iRead;

                            // Populate the sample
                            hr = PopulateSample(pData, cbData, out iRead);
                            if (hr >= 0)
                            {
                                if (hr == S_Ok) // 1 == End of stream
                                {
                                    // increment the frame number for next time
                                    m_iFrameNumber++;
                                }
                                else
                                {
                                    m_iFrameNumber = 0;
                                }

                                pSample.SetActualDataLength(iRead);
                            }
                        }
                    }
                }
            }
            finally
            {
                // Release our pointer the the media sample.  THIS IS ESSENTIAL!  If
                // you don't do this, the graph will stop after about 2 samples.
                Marshal.ReleaseComObject(pSample);
            }

            return hr;
        }
Example #32
0
        /// <summary>
        /// This routine populates the MediaSample.
        /// </summary>
        /// <param name="pSample">Pointer to a sample</param>
        /// <returns>0 = success, 1 = end of stream, negative values for errors</returns>
        public int MediaSampleCB(IMediaSample pSample)
        {
            int hr;

            try
            {
                IntPtr pData;

                hr = pSample.GetPointer(out pData);
                if (hr >= 0)
                {
                    hr = pSample.SetSyncPoint(true);
                    if (hr >= 0)
                    {
                        var len = Source.Read(pData, Constants.DShowNumberOfPacketsTS);
                        if (len != 0)
                        {
                            hr = 0;
                            pSample.SetActualDataLength(len);
                        }
                        else
                        {
                            //hr = 1;
                            hr = 0;
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Log.ErrorException("Error in Sample handler.", ex);
                hr = -1;
            }
            finally
            {
                Marshal.ReleaseComObject(pSample);
            }

            return hr;
        }
Example #33
0
        /// <summary>
        /// Implementation of ISampleGrabberCB.
        /// </summary>
        int ISampleGrabberCB.SampleCB(double sampleTime, IMediaSample pSample)
        {
            IntPtr pBuffer;
            int hr = pSample.GetPointer(out pBuffer);
            DsError.ThrowExceptionForHR(hr);

            Analyze(sampleTime, pBuffer, pSample.GetSize());

            Marshal.ReleaseComObject(pSample);
            return 0;
        }
Example #34
0
        int ISampleGrabberCB.SampleCB(double sampleTime, IMediaSample sample)
        {
            if (!_gotPicture)
            {
                // Set bGotOne to prevent further calls until we
                // request a new bitmap.
                _gotPicture = true;
                IntPtr pBuffer;

                sample.GetPointer(out pBuffer);

                if (sample.GetSize() > _stride * _height)
                {
                    throw new Exception("Buffer is wrong size");
                }

                CopyMemory(_handle, pBuffer, _stride * _height);

                _pictureReadyResetEvent.Set();
            }

            Marshal.ReleaseComObject(sample);
            return 0;
        }
Example #35
0
        /// <summary> sample callback, NOT USED. </summary>
        int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
        {
            if (!m_bGotOne)
            {
                // Set bGotOne to prevent further calls until we
                // request a new bitmap.
                m_bGotOne = true;
                IntPtr pBuffer;

                pSample.GetPointer(out pBuffer);
                int iBufferLen = pSample.GetSize();

                if (pSample.GetSize() > m_stride*m_videoHeight)
                {
                    throw new Exception("Buffer is wrong size");
                }

                NativeMethods.CopyMemory(m_handle, pBuffer, m_stride*m_videoHeight);

                // Picture is ready.
                m_PictureReady.Set();
            }

            Marshal.ReleaseComObject(pSample);
            return 0;
        }
 public int SyncReadAligned(IMediaSample pSample)
 {
     Monitor.Enter(this);
     long start, end;
     long mediaStart, mediaEnd;
     int size;
     int offset;
     int hr;
     int ans = S_OK;
     IntPtr ptr = new IntPtr();
     hr = pSample.GetPointer(out ptr);
     hr = pSample.GetTime(out start, out end);
     hr = pSample.GetMediaTime(out mediaStart, out mediaEnd);
     size = pSample.GetSize();
     int rescale = DS_RESCALE_FACTOR; // (int)((end - start) / size);
     //start += startTime;
     offset = (int)(start / rescale);
     if ((offset + size) > reader.BufferSize)
     {
         Memory.Set(ptr, offset, size);
         log.InfoFormat("SyncReadAligned went off the end ({0}, {1}, {2})", offset, (offset + size), reader.BufferSize);
         size = (int)(reader.BufferSize - offset);
         ans = S_FALSE;
     }
     if ((offset + size) > reader.BufferEnd)
     {
         log.InfoFormat("SyncReadAligned wait for buffer ({0}, {1}, {2})", offset, (offset + size), reader.BufferEnd);
         BufferData(offset + size);
     }
     log.InfoFormat("SyncReadAligned ({0} / {1} ({2}), {3} / {4}) - {5}, {6}", start, mediaStart, offset, end, mediaEnd, size, rescale);
     byte[] buffer = reader.GetBuffer();
     Marshal.Copy(buffer, offset, ptr, size);
     reader.ReleaseBuffer();
     Monitor.Exit(this);
     return ans;
 }
Example #37
0
        /// <summary>
        /// Called by the GenericSampleSourceFilter.  This routine populates the MediaSample.
        /// </summary>
        /// <param name="pSample">Pointer to a sample</param>
        /// <returns>0 = success, 1 = end of stream, negative values for errors</returns>
        public virtual int SampleCallback(IMediaSample pSample)
        {
            int hr;
            IntPtr pData;

            try
            {
                // Get the buffer into which we will copy the data
                hr = pSample.GetPointer(out pData);
                if (hr >= 0)
                {
                    // Set TRUE on every sample for uncompressed frames
                    hr = pSample.SetSyncPoint(true);
                    if (hr >= 0)
                    {
                        // Find out the amount of space in the buffer
                        int cbData = pSample.GetSize();

                        hr = SetTimeStamps(pSample);
                        if (hr >= 0)
                        {
                            int iRead;

                            // Get copy the data into the sample
                            hr = GetImage(m_iFrameNumber, pData, cbData, out iRead);
                            if (hr == 0) // 1 == End of stream
                            {
                                pSample.SetActualDataLength(iRead);

                                // increment the frame number for next time
                                m_iFrameNumber++;
                            }
                        }
                    }
                }
            }
            finally
            {
                // Release our pointer the the media sample.  THIS IS ESSENTIAL!  If
                // you don't do this, the graph will stop after about 2 samples.
                Marshal.ReleaseComObject(pSample);
            }

            return hr;
        }
        int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
        {
            if (!gotOne)
            {
                gotOne = true;
                IntPtr pBuffer;

                pSample.GetPointer(out pBuffer);
                pSample.GetSize();

                if (pSample.GetSize() > Stride*Height)
                    throw new Exception("Buffer is wrong size");

                Kernel32.CopyMemory(handle, pBuffer, Stride * Height);
                pictureReady.Set();
            }

            Marshal.ReleaseComObject(pSample);
            return 0;
        }