public Bitmap GetNextFrame(out long frameId)
        {
            if (latestBitmap == null)
            {
                frameId = -1;
                return(null);
            }

            if (!firstFrameReceived)
            {
                crossbarHelper.SetupTunerAndCrossbar(capBuilder, deviceFilter);
                firstFrameReceived = true;
            }

            Bitmap rv = null;

            NonBlockingLock.Lock(
                NonBlockingLock.LOCK_ID_GetNextFrame,
                () =>
            {
                rv = (Bitmap)latestBitmap.Clone();
            });

            frameId = frameCounter;
            return(rv);
        }
        /// <summary> buffer callback, COULD BE FROM FOREIGN THREAD. </summary>
        int ISampleGrabberCB.BufferCB(double SampleTime, IntPtr pBuffer, int BufferLen)
        {
            NonBlockingLock.Lock(
                NonBlockingLock.LOCK_ID_BufferCB,
                () =>
            {
                CopyBitmap(pBuffer);

                frameCounter++;
            });

            Thread.Sleep(1);

            return(0);
        }
        private void CloseInterfaces()
        {
            try
            {
                Thread.Sleep(50);

                if (mediaCtrl != null)
                {
                    NonBlockingLock.ExclusiveLock(
                        NonBlockingLock.LOCK_ID_CloseInterfaces,
                        () =>
                    {
                        Application.DoEvents();

                        // Stop the graph
                        int hr = mediaCtrl.Stop();
                        DsError.ThrowExceptionForHR(hr);
                    });

                    mediaCtrl = null;
                    isRunning = false;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

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

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