示例#1
0
        //-------------------------------------------------------------------
        // SetDevice
        //
        // Set up preview for a specified video capture device.
        //-------------------------------------------------------------------

        public int SetDevice(MfDevice pDevice, ref string format)
        {
            int            hr;
            IMFMediaSource pSource = null;

            lock (LockSync)
            {
                try
                {
                    // Release the current device, if any.
                    hr        = CloseDevice();
                    pActivate = pDevice.Activator;
                    object o = null;
                    if (Succeeded(hr))
                    {
                        // Create the media source for the device.
                        hr = pActivate.ActivateObject(typeof(IMFMediaSource).GUID, out o);
                    }

                    if (Succeeded(hr))
                    {
                        pSource = (IMFMediaSource)o;
                    }

                    // Get Symbolic device link
                    PwszSymbolicLink = pDevice.SymbolicName;

                    // Create the source reader.
                    if (Succeeded(hr))
                    {
                        hr = OpenMediaSource(pSource, ref PReader);
                    }

                    if (Succeeded(hr))
                    {
                        var index = GetOptimizedFormatIndex(ref format);
                        if (index >= 0)
                        {
                            hr = ConfigureSourceReader(index);
                        }
                    }

                    if (Failed(hr))
                    {
                        pSource?.Shutdown();
                        //pActivate.ShutdownObject();
                        // NOTE: The source reader shuts down the media source
                        // by default, but we might not have gotten that far.
                        CloseDevice();
                    }
                }
                finally
                {
                    SafeRelease(pSource);
                }
            }

            return(hr);
        }
示例#2
0
        public static ComObject <T> ActivateObject <T>(this IMFActivate input, Guid riid)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            if (input.ActivateObject(riid, out var pv).IsError)
            {
                return(null);
            }

            return(new ComObject <T>((T)pv));
        }
示例#3
0
        public static IComObject <T> ActivateObject <T>(this IMFActivate obj, Guid riid, bool throwOnError = true)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            obj.ActivateObject(riid, out var pv).ThrowOnError(throwOnError);
            if (pv == null)
            {
                return(null);
            }

            return(new ComObject <T>((T)pv));
        }
示例#4
0
        public MediaFoundationCapturer(IMFActivate devsource)
        {
            MediaFoundationApi.Startup();
            WaveFormat format = new WaveFormat();

            try
            {
                devsource.ActivateObject(typeof(IMFMediaSource).GUID, out object _source);
                source = _source as IMFMediaSource;
            }
            catch (COMException)
            {
                throw new ArgumentException("Can't create media source with the devsource.");
            }
            SetFormat(format);
            recordthread = new Thread(DoRecord);
        }
示例#5
0
    ///////////////////////////////////////////////////////////////////////
    //  Name: BeginEnableContent
    //  Description:  Called by the PMP session to start the enable action.
    /////////////////////////////////////////////////////////////////////////

    public HResult BeginEnableContent(
        IMFActivate pEnablerActivate,
        IMFTopology pTopo,
        IMFAsyncCallback pCallback,
        object punkState
        )
    {
        // Make sure we *never* leave this entry point with an exception
        try
        {
            Debug.WriteLine("ContentProtectionManager::BeginEnableContent");

            if (m_pEnabler != null)
            {
                throw new COMException("A previous call is still pending", (int)HResult.E_FAIL);
            }

            HResult hr;

            // Save so we can create an async result later
            m_pCallback = pCallback;
            m_punkState = punkState;

            // Create the enabler from the IMFActivate pointer.
            object o;
            hr = pEnablerActivate.ActivateObject(typeof(IMFContentEnabler).GUID, out o);
            MFError.ThrowExceptionForHR(hr);
            m_pEnabler = o as IMFContentEnabler;

            // Notify the application. The application will call DoEnable from the app thread.
            m_state = Enabler.Ready; // Reset the state.
            PostMessage(m_hwnd, WM_APP_CONTENT_ENABLER, IntPtr.Zero, IntPtr.Zero);

            return(HResult.S_OK);
        }
        catch (Exception e)
        {
            return((HResult)Marshal.GetHRForException(e));
        }
    }
        /// <summary>
        /// Creates the object associated with this activation object.
        /// </summary>
        /// <typeparam name="T">The requested COM interface.</typeparam>
        /// <param name="activate">A valid IMFActivate instance.</param>
        /// <param name="activatedObject">The requested interface.</param>
        /// <returns>If this function succeeds, it returns the S_OK member. Otherwise, it returns another HResult's member that describe the error.</returns>
        public static HResult ActivateObject <T>(this IMFActivate activate, out T activatedObject) where T : class
        {
            if (activate == null)
            {
                throw new ArgumentNullException("activate");
            }

            Type typeOfT = typeof(T);

            if (!typeOfT.IsInterface)
            {
                throw new ArgumentOutOfRangeException("T", "T must be a COM visible interface.");
            }

            object tmp;

            HResult hr = activate.ActivateObject(typeOfT.GUID, out tmp);

            activatedObject = hr.Succeeded() ? tmp as T : null;

            return(hr);
        }
示例#7
0
        //-------------------------------------------------------------------
        // SetDevice
        //
        // Set up preview for a specified video capture device.
        //-------------------------------------------------------------------

        public HResult SetDevice(MFDevice pDevice)
        {
            HResult hr = HResult.S_OK;

            IMFActivate    pActivate   = pDevice.Activator;
            IMFMediaSource pSource     = null;
            IMFAttributes  pAttributes = null;
            object         o           = null;

            lock (this)
            {
                try
                {
                    // Release the current device, if any.
                    hr = CloseDevice();

                    if (Succeeded(hr))
                    {
                        // Create the media source for the device.
                        hr = pActivate.ActivateObject(typeof(IMFMediaSource).GUID, out o);
                    }

                    if (Succeeded(hr))
                    {
                        pSource = (IMFMediaSource)o;
                    }

                    // Get Symbolic device link
                    m_pwszSymbolicLink = pDevice.SymbolicName;

                    //
                    // Create the source reader.
                    //

                    // Create an attribute store to hold initialization settings.

                    if (Succeeded(hr))
                    {
                        hr = MFExtern.MFCreateAttributes(out pAttributes, 2);
                    }

                    if (Succeeded(hr))
                    {
                        hr = pAttributes.SetUINT32(MFAttributesClsid.MF_READWRITE_DISABLE_CONVERTERS, 1);
                    }

                    if (Succeeded(hr))
                    {
                        hr = pAttributes.SetUnknown(MFAttributesClsid.MF_SOURCE_READER_ASYNC_CALLBACK, this);
                    }

                    IMFSourceReader pRead = null;
                    if (Succeeded(hr))
                    {
                        hr = MFExtern.MFCreateSourceReaderFromMediaSource(pSource, pAttributes, out pRead);
                    }

                    if (Succeeded(hr))
                    {
                        m_pReader = (IMFSourceReaderAsync)pRead;
                    }

                    if (Succeeded(hr))
                    {
                        // Try to find a suitable output type.
                        for (int i = 0; ; i++)
                        {
                            IMFMediaType pType;
                            hr = m_pReader.GetNativeMediaType((int)MF_SOURCE_READER.FirstVideoStream, i, out pType);
                            if (Failed(hr))
                            {
                                break;
                            }

                            try
                            {
                                hr = TryMediaType(pType);
                                if (Succeeded(hr))
                                {
                                    // Found an output type.
                                    break;
                                }
                            }
                            finally
                            {
                                SafeRelease(pType);
                            }
                        }
                    }

                    if (Succeeded(hr))
                    {
                        // Ask for the first sample.
                        hr = m_pReader.ReadSample((int)MF_SOURCE_READER.FirstVideoStream, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                    }

                    if (Failed(hr))
                    {
                        if (pSource != null)
                        {
                            pSource.Shutdown();

                            // NOTE: The source reader shuts down the media source
                            // by default, but we might not have gotten that far.
                        }
                        CloseDevice();
                    }
                }
                finally
                {
                    SafeRelease(pSource);
                    SafeRelease(pAttributes);
                }
            }

            return(hr);
        }
示例#8
0
        protected void CreateOutputNode(
            IMFStreamDescriptor pSourceSD,
            out IMFTopologyNode ppNode
            )
        {
            IMFTopologyNode     pNode             = null;
            IMFMediaTypeHandler pHandler          = null;
            IMFActivate         pRendererActivate = null;

            Guid guidMajorType = Guid.Empty;
            int  hr            = S_Ok;

            // Get the stream ID.
            int streamID = 0;

            try
            {
                try
                {
                    pSourceSD.GetStreamIdentifier(out streamID); // Just for debugging, ignore any failures.
                }
                catch
                {
                    TRACE("IMFStreamDescriptor::GetStreamIdentifier" + hr.ToString());
                }

                // Get the media type handler for the stream.
                pSourceSD.GetMediaTypeHandler(out pHandler);

                // Get the major media type.
                pHandler.GetMajorType(out guidMajorType);

                // Create a downstream node.
                MFExtern.MFCreateTopologyNode(MFTopologyType.OutputNode, out pNode);

                // Create an IMFActivate object for the renderer, based on the media type.
                if (MFMediaType.Audio == guidMajorType)
                {
                    // Create the audio renderer.
                    TRACE(string.Format("Stream {0}: audio stream", streamID));
                    MFExtern.MFCreateAudioRendererActivate(out pRendererActivate);
                }
                else if (MFMediaType.Video == guidMajorType)
                {
                    // Create the video renderer.
                    TRACE(string.Format("Stream {0}: video stream", streamID));
                    MFExtern.MFCreateVideoRendererActivate(m_hwndVideo, out pRendererActivate);

                    object ppv;
                    pRendererActivate.ActivateObject(typeof(IMFVideoRenderer).GUID, out ppv);

                    var renderer = ppv as IMFVideoRenderer;
                    m_customPresenter = EvrPresenter.CreateNew();
                    m_customPresenter.NewAllocatorFrame   += m_customPresenter_NewAllocatorFrame;
                    m_customPresenter.NewAllocatorSurface += m_customPresenter_NewAllocatorSurface;
                    var presenter = m_customPresenter.VideoPresenter as IMFVideoDisplayControl;
                    hr = presenter.SetVideoWindow(m_hwndVideo);
                    hr = renderer.InitializeRenderer(null, m_customPresenter.VideoPresenter);
                    var settings = presenter as IEVRPresenterSettings;
                    settings.SetBufferCount(5);
                }
                else
                {
                    TRACE(string.Format("Stream {0}: Unknown format", streamID));
                    throw new COMException("Unknown format", E_Fail);
                }

                // Set the IActivate object on the output node.
                pNode.SetObject(pRendererActivate);

                // Return the IMFTopologyNode pointer to the caller.
                ppNode = pNode;
            }
            catch
            {
                // If we failed, release the pNode
                SafeRelease(pNode);
                throw;
            }
            finally
            {
                // Clean up.
                SafeRelease(pHandler);
                SafeRelease(pRendererActivate);
            }
        }
示例#9
0
        protected IMFTopologyNode CreateOutputNode(IMFStreamDescriptor pSourceSD)
        {
            IMFTopologyNode     pNode             = null;
            IMFMediaTypeHandler pHandler          = null;
            IMFActivate         pRendererActivate = null;

            Guid guidMajorType = Guid.Empty;
            int  hr            = 0;

            // Get the stream ID.
            int streamID = 0;

            try
            {
                try
                {
                    hr = pSourceSD.GetStreamIdentifier(out streamID); // Just for debugging, ignore any failures.
                    MFError.ThrowExceptionForHR(hr);
                }
                catch
                {
                    //TRACE("IMFStreamDescriptor::GetStreamIdentifier" + hr.ToString());
                }

                // Get the media type handler for the stream.
                hr = pSourceSD.GetMediaTypeHandler(out pHandler);
                MFError.ThrowExceptionForHR(hr);

                // Get the major media type.
                hr = pHandler.GetMajorType(out guidMajorType);
                MFError.ThrowExceptionForHR(hr);

                // Create a downstream node.
                hr = MFExtern.MFCreateTopologyNode(MFTopologyType.OutputNode, out pNode);
                MFError.ThrowExceptionForHR(hr);

                // Create an IMFActivate object for the renderer, based on the media type.
                if (MFMediaType.Audio == guidMajorType)
                {
                    // Create the audio renderer.
                    hr = MFExtern.MFCreateAudioRendererActivate(out pRendererActivate);
                    MFError.ThrowExceptionForHR(hr);
                    object sar;
                    pRendererActivate.ActivateObject(typeof(IMFMediaSink).GUID, out sar);
                    StreamingAudioRenderer = sar as IMFMediaSink;
                }
                else if (MFMediaType.Video == guidMajorType)
                {
                    // Create the video renderer.
                    pRendererActivate = CreateVideoRenderer();
                }
                else
                {
                    //TRACE(string.Format("Stream {0}: Unknown format", streamID));
                    throw new COMException("Unknown format");
                }

                // Set the IActivate object on the output node.
                hr = pNode.SetObject(pRendererActivate);
                MFError.ThrowExceptionForHR(hr);
            }
            catch (Exception ex)
            {
                // If we failed, release the pNode
                COMBase.SafeRelease(pNode);
                throw;
            }
            finally
            {
                // Clean up.
                COMBase.SafeRelease(pHandler);
                COMBase.SafeRelease(pRendererActivate);
            }
            return(pNode);
        }
示例#10
0
    ///////////////////////////////////////////////////////////////////////
    //  Name: BeginEnableContent
    //  Description:  Called by the PMP session to start the enable action.
    /////////////////////////////////////////////////////////////////////////
    public int BeginEnableContent(
        IMFActivate pEnablerActivate,
        IMFTopology pTopo,
        IMFAsyncCallback pCallback,
        object punkState
        )
    {
        // Make sure we *never* leave this entry point with an exception
        try
        {
            Debug.WriteLine("ContentProtectionManager::BeginEnableContent");

            if (m_pEnabler != null)
            {
                throw new COMException("A previous call is still pending", E_Fail);
            }

            int hr;

            // Save so we can create an async result later
            m_pCallback = pCallback;
            m_punkState = punkState;

            // Create the enabler from the IMFActivate pointer.
            object o;
            hr = pEnablerActivate.ActivateObject(typeof(IMFContentEnabler).GUID, out o);
            MFError.ThrowExceptionForHR(hr);
            m_pEnabler = o as IMFContentEnabler;

            // Notify the application. The application will call DoEnable from the app thread.
            m_state = Enabler.Ready; // Reset the state.
            PostMessage(m_hwnd, WM_APP_CONTENT_ENABLER, IntPtr.Zero, IntPtr.Zero);

            return S_Ok;
        }
        catch (Exception e)
        {
            return Marshal.GetHRForException(e);
        }
    }
示例#11
0
        public HResult StartCapture(
            IMFActivate pActivate,
            string pwszFileName,
            EncodingParameters param
            )
        {
            HResult hr = HResult.S_OK;

            IMFMediaSource pSource = null;
            object         pS;

            lock (this)
            {
                // Create the media source for the device.
                hr = pActivate.ActivateObject(
                    typeof(IMFMediaSource).GUID,
                    out pS
                    );
                pSource = (IMFMediaSource)pS;

                // Get the symbolic link. This is needed to handle device-
                // loss notifications. (See CheckDeviceLost.)

                if (Succeeded(hr))
                {
                    int iSize;
                    hr = pActivate.GetAllocatedString(
                        MFAttributesClsid.MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,
                        out m_pwszSymbolicLink,
                        out iSize
                        );
                }

                if (Succeeded(hr))
                {
                    hr = OpenMediaSource(pSource);
                }

                // Create the sink writer
                if (Succeeded(hr))
                {
                    hr = MFExtern.MFCreateSinkWriterFromURL(
                        pwszFileName,
                        null,
                        null,
                        out m_pWriter
                        );
                }

                // Set up the encoding parameters.
                if (Succeeded(hr))
                {
                    hr = ConfigureCapture(param);
                }

                if (Succeeded(hr))
                {
                    m_bFirstSample = true;
                    m_llBaseTime   = 0;

                    // Request the first video frame.

                    hr = m_pReader.ReadSample(
                        MF_SOURCE_READER_FIRST_VIDEO_STREAM,
                        0,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        IntPtr.Zero
                        );
                }

                SafeRelease(pSource);
            }

            return(hr);
        }
示例#12
0
        public int StartCapture(
            IMFActivate pActivate,
            string pwszFileName,
            EncodingParameters param
            )
        {
            int hr = S_Ok;

            IMFMediaSource pSource = null;
            object pS;

            lock (this)
            {
                // Create the media source for the device.
                hr = pActivate.ActivateObject(
                    typeof(IMFMediaSource).GUID,
                    out pS
                    );
                pSource = (IMFMediaSource)pS;

                // Get the symbolic link. This is needed to handle device-
                // loss notifications. (See CheckDeviceLost.)

                if (Succeeded(hr))
                {
                    int iSize;
                    hr = pActivate.GetAllocatedString(
                        MFAttributesClsid.MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,
                        out m_pwszSymbolicLink,
                        out iSize
                        );
                }

                if (Succeeded(hr))
                {
                    hr = OpenMediaSource(pSource);
                }

                // Create the sink writer
                if (Succeeded(hr))
                {
                    hr = MFExtern.MFCreateSinkWriterFromURL(
                        pwszFileName,
                        null,
                        null,
                        out m_pWriter
                        );
                }

                // Set up the encoding parameters.
                if (Succeeded(hr))
                {
                    hr = ConfigureCapture(param);
                }

                if (Succeeded(hr))
                {
                    m_bFirstSample = true;
                    m_llBaseTime = 0;

                    // Request the first video frame.

                    hr = m_pReader.ReadSample(
                        MF_SOURCE_READER_FIRST_VIDEO_STREAM,
                        0,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        IntPtr.Zero
                        );
                }

                SafeRelease(pSource);
            }

            return hr;
        }
示例#13
0
        //-------------------------------------------------------------------
        // SetDevice
        //
        // Set up preview for a specified video capture device.
        //-------------------------------------------------------------------
        public int SetDevice(MfDevice pDevice, ref string format)
        {
            int hr;
            IMFMediaSource pSource = null;
            lock (LockSync)
            {
                try
                {
                    // Release the current device, if any.
                    hr = CloseDevice();
                    pActivate = pDevice.Activator;
                    object o = null;
                    if (Succeeded(hr))
                    {
                        // Create the media source for the device.
                        hr = pActivate.ActivateObject(typeof(IMFMediaSource).GUID, out o);
                    }

                    if (Succeeded(hr))
                    {
                        pSource = (IMFMediaSource)o;
                    }

                    // Get Symbolic device link
                    PwszSymbolicLink = pDevice.SymbolicName;

                    // Create the source reader.
                    if (Succeeded(hr))
                    {
                        hr = OpenMediaSource(pSource, ref PReader);
                    }

                    if (Succeeded(hr))
                    {
                        var index = GetOptimizedFormatIndex(ref format);
                        if (index>=0)
                            hr = ConfigureSourceReader(index);
                    }

                    if (Failed(hr))
                    {

                        pSource?.Shutdown();
                        //pActivate.ShutdownObject();
                        // NOTE: The source reader shuts down the media source
                        // by default, but we might not have gotten that far.
                        CloseDevice();
                    }
                }
                finally
                {
                    SafeRelease(pSource);
                }
            }

            return hr;
        }