Search code examples
c#c++mediaaccess-violationfoundation

Media Foundation: ReadSample - Access Violation Exception


Context: I'm looking at the effects of down sampling, then up sampling video files. I'm using Media Foundation .NET to expose MF in C#. Program currently goes through following process:

  • Take a high res video and read in each frame (SourceReader & ReadSample)
  • Down sample using custom code that manipulates at the byte level
  • Write the down sampled data to a new, lower res video file (using SinkWriter)
  • Repeat for a range of resolutions supported by Media Foundation
  • Read down sampled videos back in and up sample to the next higher resolution in the list below, again using custom code that manipulates each byte
  • Write the new data to a higher res file (again using SinkWriter)

Resolutions I'm using are:

  • 2560,1440
  • 2346,1320
  • 2134,1200
  • 1920,1080
  • 1706,960
  • 1494,840
  • 1280,720
  • 1068,600
  • 854,480
  • 640,360
  • 428,240
  • 214,120

Current situation: This works almost perfectly. I run through the down sample process and have 11 down sampled video files (one at each resolution in the list above), plus the original 1440p video. I then read in each of those 11 videos and up sample. It works for 10 of them.

The problem: when I try to take the (1280,720) video to up sample to (1494,840), I get:

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

... when I try to read in the first frame. I can't figure out why. The SourceReader configures fine (at least, no error returns). I do things like Marshal.Copy to get the sampled frame data into managed memory space, which I initially assumed was the problem. Code doesn't get that far though - just errors as soon as I try to read the first frame sample. ReadSample is in a Try...Catch block, but exception remains unhandled, so no other error information returned.

I don't want to just start pasting in unhelpful code, so please let me know what is useful to see and I'll add to the question. Most of the code has been taken from MS tutorials for SourceReader and SinkWriter. Also worth keeping in mind that this works in most situations, so code isn't 'broken' as such.

I've tried compiling in Release and Debug, x86 and x64. Also tried Suppressing JIT Optimisation in Visual Studio options.

Any ideas on where to look next?


Solution

  • Turns out this is a problem with the Media Foundation .NET interface, not the underlying MF framework. I built a small test program in C++ that implemented key parts of the code and it went through fine.

    Not sure why Media Foundation .NET was causing problems, but the solution was just to set attribute: MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING rather than MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING

    With advanced processing on, it behaves properly.