/// <summary>
        /// Creates a memory buffer of the specified size
        /// </summary>
        /// <param name="bufferSize">Memory buffer size in bytes</param>
        /// <returns>The memory buffer</returns>
        public static IMFMediaBuffer CreateMemoryBuffer(int bufferSize)
        {
            IMFMediaBuffer buffer;

            MediaFoundationInterop.MFCreateMemoryBuffer(bufferSize, out buffer);
            return(buffer);
        }
Пример #2
0
        public static IMFMediaType CreateMediaType()
        {
            IMFMediaType result;

            MediaFoundationInterop.MFCreateMediaType(out result);
            return(result);
        }
        /// <summary>
        /// Creates a new attributes store
        /// </summary>
        /// <param name="initialSize">Initial size</param>
        /// <returns>The attributes store</returns>
        public static IMFAttributes CreateAttributes(int initialSize)
        {
            IMFAttributes attributes;

            MediaFoundationInterop.MFCreateAttributes(out attributes, initialSize);
            return(attributes);
        }
        /// <summary>
        /// Creates a sample object
        /// </summary>
        /// <returns>The sample object</returns>
        public static IMFSample CreateSample()
        {
            IMFSample sample;

            MediaFoundationInterop.MFCreateSample(out sample);
            return(sample);
        }
        /// <summary>
        /// Creates a source reader based on a byte stream
        /// </summary>
        /// <param name="byteStream">The byte stream</param>
        /// <returns>A media foundation source reader</returns>
        public static IMFSourceReader CreateSourceReaderFromByteStream(IMFByteStream byteStream)
        {
            IMFSourceReader reader;

            MediaFoundationInterop.MFCreateSourceReaderFromByteStream(byteStream, null, out reader);
            return(reader);
        }
        /// <summary>
        /// Creates a media foundation byte stream based on a stream object
        /// (usable with WinRT streams)
        /// </summary>
        /// <param name="stream">The input stream</param>
        /// <returns>A media foundation byte stream</returns>
        public static IMFByteStream CreateByteStream(object stream)
        {
            IMFByteStream byteStream;

            MediaFoundationInterop.MFCreateMFByteStreamOnStreamEx(stream, out byteStream);
            return(byteStream);
        }
        /// <summary>
        /// Creates a Media type
        /// </summary>
        public static IMFMediaType CreateMediaType()
        {
            IMFMediaType mediaType;

            MediaFoundationInterop.MFCreateMediaType(out mediaType);
            return(mediaType);
        }
Пример #8
0
        public static IMFAttributes CreateAttributes(int initialSize)
        {
            IMFAttributes result;

            MediaFoundationInterop.MFCreateAttributes(out result, initialSize);
            return(result);
        }
Пример #9
0
        public static IMFSample CreateSample()
        {
            IMFSample result;

            MediaFoundationInterop.MFCreateSample(out result);
            return(result);
        }
 /// <summary>
 /// initializes MediaFoundation - only needs to be called once per process
 /// </summary>
 public static void Startup()
 {
     if (!initialized)
     {
         MediaFoundationInterop.MFStartup(MediaFoundationInterop.MF_VERSION, 0);
         initialized = true;
     }
 }
 /// <summary>
 /// uninitializes MediaFoundation
 /// </summary>
 public static void Shutdown()
 {
     if (initialized)
     {
         MediaFoundationInterop.MFShutdown();
         initialized = false;
     }
 }
Пример #12
0
        public static IEnumerable <IMFActivate> EnumDeviceSources()
        {
            IMFAttributes devtype = CreateAttributes(2);
            Guid          MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID = new Guid(0x14dd9a1c, 0x7cff, 0x41be, 0xb1, 0xb9, 0xba, 0x1a, 0xc6, 0xec, 0xb5, 0x71);

            devtype.SetGUID(MediaFoundationAttributes.MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID);
            MediaFoundationInterop.MFEnumDeviceSources(devtype, out IMFActivate[] sources, out _);
            foreach (var i in sources)
            {
                yield return(i);
            }
        }
Пример #13
0
 public static void Startup()
 {
     if (!MediaFoundationApi.initialized)
     {
         int             num       = 2;
         OperatingSystem osversion = Environment.OSVersion;
         if (osversion.Version.Major == 6 && osversion.Version.Minor == 0)
         {
             num = 1;
         }
         MediaFoundationInterop.MFStartup(num << 16 | 112, 0);
         MediaFoundationApi.initialized = true;
     }
 }
Пример #14
0
        /// <summary>
        /// Processes the media session event.
        /// </summary>
        private void ProcessEvent()
        {
            while (m_Session != null)
            {
                try {
                    m_Session.GetEvent(1, out IMFMediaEvent _event);//requests events and returns immediately
                    _event.GetType(out MediaEventType eventtype);
                    switch (eventtype)
                    {
                    case MediaEventType.MESessionEnded:
                        PlaybackState = PlaybackState.Stopped;
                        PlaybackStopped?.Invoke(this, new StoppedEventArgs());
                        break;

                    case MediaEventType.MESessionTopologyStatus:    //topology loaded
                        Guid guidManager = typeof(IAudioSessionManager).GUID;
                        (new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator).
                        GetDefaultAudioEndpoint(CoreAudioApi.DataFlow.Render, CoreAudioApi.Role.Multimedia, out IMMDevice endoint);
                        endoint.Activate(ref guidManager, ClsCtx.ALL, IntPtr.Zero, out object _manager);
                        IAudioSessionManager manager = _manager as IAudioSessionManager;
                        manager.GetSimpleAudioVolume(Guid.Empty, 0, out m_volume);

                        m_Session.GetClock(out m_clock);

                        Guid guid_ratecontrol        = typeof(IMFRateControl).GUID;
                        Guid MF_RATE_CONTROL_SERVICE = Guid.Parse("866fa297-b802-4bf8-9dc9-5e3b6a9f53c9");
                        MediaFoundationInterop.MFGetService(m_Session, ref MF_RATE_CONTROL_SERVICE, ref guid_ratecontrol, out object _control);    //gets rate control
                        m_rate   = _control as IMFRateControl;
                        Prepared = true;
                        break;
                    }
                    _event = null;
                }
                catch (COMException e)
                {
                    if (e.HResult == MediaFoundationErrors.MF_E_NO_EVENTS_AVAILABLE)
                    {
                        continue;
                    }
                    else
                    {
                        throw e;
                    }
                }
                catch (ThreadAbortException)
                {
                    break;
                }
            }
        }
        /// <summary>
        /// Creates a media type from a WaveFormat
        /// </summary>
        public static IMFMediaType CreateMediaTypeFromWaveFormat(WaveFormat waveFormat)
        {
            var mediaType = CreateMediaType();

            try
            {
                MediaFoundationInterop.MFInitMediaTypeFromWaveFormatEx(mediaType, waveFormat, Marshal.SizeOf(waveFormat));
            }
            catch (Exception)
            {
                Marshal.ReleaseComObject(mediaType);
                throw;
            }
            return(mediaType);
        }
Пример #16
0
        /// <summary>
        /// initializes MediaFoundation - only needs to be called once per process
        /// </summary>
        public static void Startup()
        {
            if (!initialized)
            {
                var sdkVersion = MediaFoundationInterop.MF_SDK_VERSION;
#if !NETFX_CORE
                var os = Environment.OSVersion;
                if (os.Version.Major == 6 && os.Version.Minor == 0)
                {
                    sdkVersion = 1;
                }
#endif
                MediaFoundationInterop.MFStartup((sdkVersion << 16) | MediaFoundationInterop.MF_API_VERSION, 0);
                initialized = true;
            }
        }
Пример #17
0
        /// <summary>
        /// Creates a media foundation byte stream based on a stream object
        /// (usable with WinRT streams)
        /// </summary>
        /// <param name="stream">The input stream</param>
        /// <returns>A media foundation byte stream</returns>
        public static IMFByteStream CreateByteStream(object stream)
        {
            IMFByteStream byteStream;

#if NETFX_CORE
            MediaFoundationInterop.MFCreateMFByteStreamOnStreamEx(stream, out byteStream);
#else
            if (stream is IStream)
            {
                MediaFoundationInterop.MFCreateMFByteStreamOnStream(stream as IStream, out byteStream);
            }
            else
            {
                throw new ArgumentException("Stream must be IStream in desktop apps");
            }
#endif
            return(byteStream);
        }
Пример #18
0
        private void SetFormat(WaveFormat format)
        {
            source.CreatePresentationDescriptor(out IMFPresentationDescriptor descriptor);
            descriptor.GetStreamDescriptorCount(out uint sdcount);
            bool hasaudio = false;

            for (uint i = 0; i < sdcount; i++)
            {
                descriptor.GetStreamDescriptorByIndex(i, out _, out IMFStreamDescriptor sd);
                descriptor.SelectStream(i);
                sd.GetMediaTypeHandler(out IMFMediaTypeHandler typeHandler);
                typeHandler.GetMediaTypeByIndex(0, out IMFMediaType mediaType);
                mediaType.GetMajorType(out Guid streamtype);
                if (streamtype == MediaTypes.MFMediaType_Audio)
                {
                    try
                    {
                        mediaType.SetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_SAMPLES_PER_SECOND, format.SampleRate);//SampleRate
                        mediaType.SetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_NUM_CHANNELS, format.Channels);
                        mediaType.SetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_BITS_PER_SAMPLE, format.BitsPerSample);
                        mediaType.SetGUID(MediaFoundationAttributes.MF_MT_SUBTYPE, AudioSubtypes.MFAudioFormat_PCM);
                    }
                    catch (COMException)
                    {
                        throw new InvalidOperationException("Can't configure the source with specific format.");
                    }
                    hasaudio = true;
                }
                else
                {
                    continue;
                }
            }
            if (!hasaudio)
            {
                throw new ArgumentException("The device doesn't have audio stream.");
            }
            this.format = format;
            IMFAttributes readerattr = MediaFoundationApi.CreateAttributes(2);

            readerattr.SetUnknown(MediaFoundationAttributes.MF_SOURCE_READER_ASYNC_CALLBACK, callback);
            MediaFoundationInterop.MFCreateSourceReaderFromMediaSource(source, readerattr, out IMFSourceReader _sourceReader);
            sourceReader = _sourceReader as IMFSourceReader2;
        }
Пример #19
0
//#if !NETFX_CORE
        /// <summary>
        /// Enumerate the installed MediaFoundation transforms in the specified category
        /// </summary>
        /// <param name="category">A category from MediaFoundationTransformCategories</param>
        /// <returns></returns>
        public static IEnumerable <IMFActivate> EnumerateTransforms(Guid category)
        {
            MediaFoundationInterop.MFTEnumEx(category, _MFT_ENUM_FLAG.MFT_ENUM_FLAG_ALL,
                                             null, null, out var interfacesPointer, out var interfaceCount);
            var interfaces = new IMFActivate[interfaceCount];

            for (int n = 0; n < interfaceCount; n++)
            {
                var ptr =
                    Marshal.ReadIntPtr(new IntPtr(interfacesPointer.ToInt64() + n * Marshal.SizeOf(interfacesPointer)));
                interfaces[n] = (IMFActivate)Marshal.GetObjectForIUnknown(ptr);
            }

            foreach (var i in interfaces)
            {
                yield return(i);
            }
            Marshal.FreeCoTaskMem(interfacesPointer);
        }
Пример #20
0
        public static IEnumerable <IMFActivate> EnumerateTransforms(Guid category)
        {
            IntPtr interfacesPointer;
            int    interfaceCount;

            MediaFoundationInterop.MFTEnumEx(category, _MFT_ENUM_FLAG.MFT_ENUM_FLAG_ALL, null, null, out interfacesPointer, out interfaceCount);
            IMFActivate[] interfaces = new IMFActivate[interfaceCount];
            for (int j = 0; j < interfaceCount; j++)
            {
                IntPtr pUnk = Marshal.ReadIntPtr(new IntPtr(interfacesPointer.ToInt64() + (long)(j * Marshal.SizeOf(interfacesPointer))));
                interfaces[j] = (IMFActivate)Marshal.GetObjectForIUnknown(pUnk);
            }
            foreach (IMFActivate i in interfaces)
            {
                yield return(i);
            }
            Marshal.FreeCoTaskMem(interfacesPointer);
            yield break;
        }
Пример #21
0
        private void Load()
        {
            MediaFoundationInterop.MFCreateSourceResolver(out IMFSourceResolver resolver);
            object unknown;

            try
            {
                resolver.CreateObjectFromURL(URL, SourceResolverFlags.MF_RESOLUTION_MEDIASOURCE | SourceResolverFlags.MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE,
                                             null, out _, out unknown);
            }
            catch
            {
                throw new ArgumentException("Unsupported type.");
            }
            MediaFoundationInterop.MFCreateMediaSession(IntPtr.Zero, out m_Session);
            MediaFoundationInterop.MFCreateTopology(out IMFTopology topo);
            IMFMediaSource source = unknown as IMFMediaSource;

            source.CreatePresentationDescriptor(out m_pDescriptor);
            m_pDescriptor.GetUINT64(MediaFoundationAttributes.MF_PD_DURATION, out long dur);
            m_Duration = dur / 10000000;
            m_pDescriptor.GetStreamDescriptorCount(out uint sdcount);
            m_streamcount = (int)sdcount;
            for (uint i = 0; i < m_streamcount; i++)
            {
                m_pDescriptor.GetStreamDescriptorByIndex(i, out bool IsSelected, out IMFStreamDescriptor sd);
                m_DefaultStreamSelect.Add(IsSelected);
                switch (StreamSelectFlag)
                {
                case StreamSelectFlags.SelectAllStream:
                    if (!IsSelected)
                    {
                        m_pDescriptor.SelectStream(i);
                    }
                    break;

                case StreamSelectFlags.SelectNone:
                    if (IsSelected)
                    {
                        m_pDescriptor.DeselectStream(i);
                    }
                    break;
                }
                sd.GetMediaTypeHandler(out IMFMediaTypeHandler typeHandler);
                typeHandler.GetMediaTypeByIndex(0, out IMFMediaType mediaType);
                mediaType.GetMajorType(out Guid streamtype);
                IMFActivate renderer;
                if (streamtype == MediaTypes.MFMediaType_Audio)
                {
                    MediaFoundationInterop.MFCreateAudioRendererActivate(out renderer);
                    mediaType.GetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_SAMPLES_PER_SECOND, out int rate);//SampleRate
                    mediaType.GetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_NUM_CHANNELS, out int channelcount);
                    int samplesize;
                    try
                    {
                        mediaType.GetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_BITS_PER_SAMPLE, out samplesize);
                    }
                    catch (COMException e)
                    {
                        if ((uint)e.HResult != 0xC00D36E6)
                        {
                            throw e;
                        }
                        else
                        {
                            samplesize = 8;
                        }
                    }
                    m_format.Add(new WaveFormat(rate, samplesize, channelcount));
                }
                else
                {
                    continue;
                }
                MediaFoundationInterop.MFCreateTopologyNode(MF_TOPOLOGY_TYPE.MF_TOPOLOGY_SOURCESTREAM_NODE, out IMFTopologyNode sourcenode);
                sourcenode.SetUnknown(MediaFoundationAttributes.MF_TOPONODE_SOURCE, source);
                sourcenode.SetUnknown(MediaFoundationAttributes.MF_TOPONODE_PRESENTATION_DESCRIPTOR, m_pDescriptor);
                sourcenode.SetUnknown(MediaFoundationAttributes.MF_TOPONODE_STREAM_DESCRIPTOR, sd);
                topo.AddNode(sourcenode);
                MediaFoundationInterop.MFCreateTopologyNode(MF_TOPOLOGY_TYPE.MF_TOPOLOGY_OUTPUT_NODE, out IMFTopologyNode outputnode);
                outputnode.SetObject(renderer);
                topo.AddNode(outputnode);
                sourcenode.ConnectOutput(0, outputnode, 0);
            }
            m_Session.SetTopology(0, topo);
            m_Eventthread = new Thread(ProcessEvent);
            m_Eventthread.Start();
        }
Пример #22
0
        /// <summary>
        /// Loads IWaveProvider.
        /// </summary>
        /// <param name="waveProvider">The waveProvider to be loaded.</param>
        public void Init(IWaveProvider waveProvider)
        {
            MediaFoundationApi.Startup();
            m_sourcewave = waveProvider;
            int          readcount;
            MemoryStream msByteStrem = new MemoryStream();

            byte[] _data;
            do
            {
                readcount = 0;
                _data     = new byte[32767];
                readcount = waveProvider.Read(_data, 0, _data.Length);
                if (readcount < 0)
                {
                    continue;
                }
                msByteStrem.Write(_data, 0, readcount);
            } while (readcount >= _data.Length | readcount < 0);//Creates a IMFByteStream and fills it with the data in waveProvider.
            ComStream     csByteStream = new ComStream(msByteStrem);
            IMFByteStream mfByteStream = MediaFoundationApi.CreateByteStream(csByteStream);

            MediaFoundationInterop.MFCreateSourceResolver(out IMFSourceResolver resolver);
            IMFAttributes streamattributes = mfByteStream as IMFAttributes;

            mfByteStream.GetLength(out long _length);
            resolver.CreateObjectFromByteStream(mfByteStream, null, SourceResolverFlags.MF_RESOLUTION_MEDIASOURCE
                                                | SourceResolverFlags.MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE, null, out _, out object _source);//Turns the stream to IMFMediaSource
            IMFMediaSource source = _source as IMFMediaSource;

            source.CreatePresentationDescriptor(out IMFPresentationDescriptor descriptor);
            MediaFoundationInterop.MFCreateTopology(out IMFTopology topo);
            descriptor.GetStreamDescriptorCount(out uint sdcount);
            for (uint i = 0; i < sdcount; i++)//For each stream in the source,creates renderer and adds to the topology.
            {
                descriptor.GetStreamDescriptorByIndex(i, out bool IsSelected, out IMFStreamDescriptor sd);
                if (!IsSelected)
                {
                    if (SelectAllStream)
                    {
                        descriptor.SelectStream(i);
                    }
                    else
                    {
                        continue;
                    }
                }
                sd.GetMediaTypeHandler(out IMFMediaTypeHandler typeHandler);
                typeHandler.GetMajorType(out Guid streamtype);
                IMFActivate renderer;
                if (streamtype == MediaTypes.MFMediaType_Audio)
                {
                    MediaFoundationInterop.MFCreateAudioRendererActivate(out renderer);//Creates renderer for audio streams
                }
                else
                {
                    continue;
                }
                //Creats and equips the topology nodes of the certain stream
                MediaFoundationInterop.MFCreateTopologyNode(MF_TOPOLOGY_TYPE.MF_TOPOLOGY_SOURCESTREAM_NODE, out IMFTopologyNode sourcenode);
                sourcenode.SetUnknown(MediaFoundationAttributes.MF_TOPONODE_SOURCE, source);
                sourcenode.SetUnknown(MediaFoundationAttributes.MF_TOPONODE_PRESENTATION_DESCRIPTOR, descriptor);
                sourcenode.SetUnknown(MediaFoundationAttributes.MF_TOPONODE_STREAM_DESCRIPTOR, sd);
                topo.AddNode(sourcenode);
                MediaFoundationInterop.MFCreateTopologyNode(MF_TOPOLOGY_TYPE.MF_TOPOLOGY_OUTPUT_NODE, out IMFTopologyNode outputnode);
                outputnode.SetObject(renderer);
                topo.AddNode(outputnode);
                sourcenode.ConnectOutput(0, outputnode, 0);
            }
            MediaFoundationInterop.MFCreateMediaSession(IntPtr.Zero, out m_Session);
            m_Session.SetTopology(0, topo);
            m_eventthread = new Thread(ProcessEvent);
            m_eventthread.Start();
        }
Пример #23
0
        /// <summary>
        /// Initialize the MediaFoundationProvider with specific file.
        /// </summary>
        public MediaFoundationProvider(string url)
        {
            MediaFoundationApi.Startup();
            if (!File.Exists(url))
            {
                throw new FileNotFoundException("This file doesn't exist");
            }
            MediaFoundationInterop.MFCreateSourceResolver(out IMFSourceResolver resolver);
            //Creates both IMFMediaSource and IMFByteStream.Uses the stream for 'Read' method and uses the source to collect format information.
            resolver.CreateObjectFromURL(url, SourceResolverFlags.MF_RESOLUTION_BYTESTREAM | SourceResolverFlags.MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE, null, out _, out object _stream);
            IMFByteStream byteStream = _stream as IMFByteStream;

            resolver.CreateObjectFromByteStream(byteStream, null, SourceResolverFlags.MF_RESOLUTION_MEDIASOURCE | SourceResolverFlags.MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE, null, out _, out object _source);
            Marshal.FinalReleaseComObject(resolver);
            IMFMediaSource source = _source as IMFMediaSource;

            source.CreatePresentationDescriptor(out IMFPresentationDescriptor descriptor);
            descriptor.GetStreamDescriptorCount(out uint sdcount);
            for (uint i = 0; i < sdcount; i++)
            {
                descriptor.GetStreamDescriptorByIndex(i, out _, out IMFStreamDescriptor sd);
                sd.GetMediaTypeHandler(out IMFMediaTypeHandler typeHandler);
                typeHandler.GetMediaTypeByIndex(0, out IMFMediaType mediaType);
                mediaType.GetMajorType(out Guid streamtype);
                if (streamtype == MediaTypes.MFMediaType_Audio)
                {
                    mediaType.GetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_SAMPLES_PER_SECOND, out int rate);//SampleRate
                    mediaType.GetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_NUM_CHANNELS, out int channelcount);
                    int samplesize;
                    try
                    {
                        mediaType.GetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_BITS_PER_SAMPLE, out samplesize);
                    }
                    catch (COMException e)
                    {
                        if ((uint)e.HResult != 0xC00D36E6)
                        {
                            throw e;
                        }
                        else
                        {
                            samplesize = 8;
                        }
                    }
                    WaveFormat = new WaveFormat(rate, samplesize, channelcount);
                }
                else
                {
                    continue;
                }
            }
            byteStream.GetLength(out streamlength);
            byteStream.SetCurrentPosition(0);
            //Moves all the bytes in IMFByteStream to MemoryStream.
            MediaFoundationInterop.MFCreateMemoryBuffer(unchecked ((int)streamlength), out IMFMediaBuffer mediabuffer);
            mediabuffer.Lock(out IntPtr pbuffer, out int length, out _);
            byteStream.Read(pbuffer, length, out _);
            byte[] buffer = new byte[length];
            Marshal.Copy(pbuffer, buffer, 0, length);
            datastream = new MemoryStream(buffer);
        }