This project has moved. For the latest updates, please go here.

MFCreateWaveFormatExFromMFMediaType exception

Jan 26, 2014 at 11:03 PM
I'm trying to get a WaveFormat from a MediaType via MediaFoundationReader but I'm not sure if this is the correct way of doing it. StructureToPtr is throwing an exception.

Line: Marshal.StructureToPtr(wfed, waveFormatPointer, false);
Exception: System.AccessViolationException: Attempted to read or write protected memory.
            IMFMediaType uncompressedMediaType;
            
            
            reader.GetCurrentMediaType(MediaFoundationInterop.MF_SOURCE_READER_FIRST_AUDIO_STREAM, out uncompressedMediaType);

            WaveFormatExtraData wfed = new WaveFormatExtraData();
            IntPtr waveFormatPointer = new IntPtr(Marshal.SizeOf(wfed));
            Marshal.StructureToPtr(wfed, waveFormatPointer, false);

            
            int size = 0;
            MediaFoundationInterop.MFCreateWaveFormatExFromMFMediaType(uncompressedMediaType, ref waveFormatPointer, ref size, 0);
            
            WaveFormat waveFormat = WaveFormat.MarshalFromPtr(waveFormatPointer);
Jan 27, 2014 at 2:43 AM
Edited Jan 27, 2014 at 6:52 AM
I got it working.

In MediaFoundationInterop.cs I had to change
internal static extern void MFCreateWaveFormatExFromMFMediaType(IMFMediaType pMFType, ref IntPtr ppWF, ref int pcbSize, int flags = 0);
to
internal static extern void MFCreateWaveFormatExFromMFMediaType(IMFMediaType pMFType, out IntPtr ppWF, out int pcbSize, int flags = 0);
This goes in MediaFoundationHelpers.cs
        /// <summary>
        /// Creates a WaveFormatExtraData from an IMFMediaType
        /// </summary>
        /// <param name="mediatype">A MediaFoundation IMFMediaType</param>
        /// <returns>A WaveFormat based on WaveFormatExtraData</returns>        
        public static WaveFormat CreateWaveFormatExFromMediaType(IMFMediaType mediatype)
        {
            WaveFormatExtraData wfed = new WaveFormatExtraData();
            IntPtr waveFormatPointer  = new IntPtr(Marshal.SizeOf(wfed));
            
            int size = 0;
            MediaFoundationInterop.MFCreateWaveFormatExFromMFMediaType(mediatype, out waveFormatPointer, out size, 0);

            return WaveFormatExtraData.MarshalFromPtr(waveFormatPointer);
                
        }    
Encoding: MpegLayer3
ExtraSize: 12
AudioSubType 00000055-0000-0010-8000-00aa00389b71
pcbsize 30

Encoding: WindowsMediaAudio
ExtraSize: 10
AudioSubType 00000161-0000-0010-8000-00aa00389b71
pcbsize 28

Encoding: MPEG_HEAAC
ExtraSize: 14
AudioSubType 00001610-0000-0010-8000-00aa00389b71
pcbsize 32

Encoding: 61868 <-- FLAC
ExtraSize: 0
AudioSubType 0000f1ac-0000-0010-8000-00aa00389b71
pcbsize 18

Encoding: Pcm
ExtraSize: 0
audioSubType 00000001-0000-0010-8000-00aa00389b71
pcbsize 18