Bug in Media Foundation MPEG-4 File Source related to timestamping video frames of a fragmented MP4 file

Some recent update in Media Foundation platform introduced a new bug related to fragmented MP4 files and H.264 video. The bug shows up consistently with file versions:

  • mfplat.dll – 10.0.14393.351 (rs1_release_inmarket.161014-1755)    15-Oct-16 05:48
  • mfmp4srcsnk.dll – 10.0.14393.351 (rs1_release_inmarket.161014-1755)    15-Oct-16 05:45

The nature of the problem is that MPEG-4 File Source is incorrectly time stamping the data: frame time stamps are incorrect, they seems to be getting wrong durations and increments, then quickly jumps into future… and on playback this leads to unobvious playback freezes. As Media Foundation is used by Windows Media Player, Windows 10 Movies & TV Player, the bug is present there as well.

The original report is on MSDN Forums.

Presumably it is possible to roll certain Windows Update package back, or alternatively one has to wait for Microsoft to fix the problem and deliver a new update deploying the fix.

Applying Hardsubs to H.264 Video with GPU

Video adapters currently offer a range of services which enables transcoding of H.264 content with certain modifications (including but not limited to flexible overlays, scaling, mirroring, effects and filters) end-to end on GPU keeping data as DirectX Graphics Infrastructure resource at all processing stages.

Such specialized processing capabilities are pretty powerful compared to traditional CPU processing, especially taking into consideration performance of low end low power-consumption systems still equipped with contemporary GPU.

For a test, I transcoded video H.264/MP4 files of different resolutions applying a text overlay having a time stamp of video frame being processed. The overlay is complex enough to be  varying frame to frame, be a standard font with respective rasterization (using DirectWrite). The test re-encoded H.264 content maintaining bitrate without giving too much care for other encoding details (defaults used).

Hardsub Performance Test

The roughly made test was successful with two video GPUs:

  1. Intel HD Graphics 4600 (7th gen; Desktop system; Core i7-4790 CPU)
  2. Intel HD Graphics (8th gen; Ultramobile system; Atom x5-Z8300 CPU) – the system is actually a $200 worth budget Chinese tablet Cube iWork 10 Ultimate

The test failed on other GPUs:

  • Intel HD Graphics 4000 (7th gen; Mobile system; Core i7-3517U CPU)
  • NVIDIA GeForce GTX 750

The problem – as it looks without getting into details – seems to be the inability of Media Foundation APIs to fit Direct3D-enabled pipelines out of the box, such as because of lack of certain conversion. It looks like transcoding can be achieved, with just putting some more effort into it.

As of now, Intel offers their 9th generation GPUs and the ones being tested are hardware of a few yeas in age…

Compared to real time performance of 100% (meaning that it takes one second to process one second of video of given metrics), both systems managed to do the transcoding relatively efficiently. With a roughly built test having a bottleneck at applying overlay, taking place serially in single thread, both systems showed performance sufficient to convert 1920×1080@60 video faster than in real time and without maxing CPU out.

Intel’s seventh generation desktop GPU managed to do the job way much faster.

It is interesting that even cheap tablet can process a Full HD video stream loading CPU less than 40%. Basically, the performance is sufficient for doing real time video processing (including using external web camera like Logitech C930E) with certain processing in 1080p resolution using budget grade hardware.

Re-encoding Performance

When there is no necessity to keep the real time processing pace, the cheap tablet showed the ability to do GPU processing on 2K video, which is also good news for those who wants to apply budget hardware to high resolution material.

Apparently, the key factor is ability of the process to keep data in video hardware. As Intel GPU H.264 abilities scale well when used for concurrent multi-stream processing, the performance numbers promise great performance recording video in several formats at a time: raw video, video with overlay, scaled down etc.

The table below gives more numbers for the tests concluded:

Re-encoding Performance Numbers

As mentioned above, the overlaying part itself is a single threaded bottleneck and presumably it is a reserve to be used to cut elapsed time down even further.

Another interesting observation is that while ultramobile system still uses much of CPU time (which is okay – it’s not a powerful system by design), the desktop GPU has minimal impact on CPU while doing pretty complicated task.

Screen recording using Desktop Duplication API and hardware H.264 encoder

The application takes advantage of three powerful Windows APIs at a time:

MediaFoundationDesktopRecorder initializes a desktop duplication session and sends obtained desktop images to H.264 video encoder producing a standard MP4 recording. Optionally, it can add an audio track capturing data from one of the standard inputs.

The best performance is achieved when used with hardware H.264 encoder: not only the performance of hardware encoder is better, but additionally desktop images are transferred to the encoder efficiently, without being copied through system memory. With respective hardware, recording is pretty efficient.

There are certain limitations: duplication API is Windows 8+, encoder availability depends on hardware and OS versions. The application let API pick encoder automatically and in worth case scenario falls back to software encoder, which is typically a performance hit.

MediaFoundationDesktopRecorder UI

When started, the application prints initial information, esp. regarding availability of devices, and appends as actions and events take place.

The application uses configuration file with the same name and location as the application, and .INI extension. Changes to the configuration file take effect when the application is restarted.

The application registers Win+F5, Win+F8 hotkeys globally to start/stop recording when the application is in background (that is, when user interacts with another application).

The application generates .MP4 files in the directory of its own location. There will be a video track, and optionally one additional audio track – depending on settings. Video is taken from one of the monitors, and audio – from one of the available standard audio input devices.

The application also generates log files at one the locations:

  • C:\ProgramData\MediaFoundationDesktopRecorder.log
  • C:\Users\$(UserName)\AppData\Local\MediaFoundationDesktopRecorder.log (in case the first path above is inaccessible, esp. due to insufficient permissions)

Configuration

The configuration .INI file might contain a few settings that set up and alter the behavoir of the application:

[Input]
;Video Adapter Description=NVIDIA GeForce GTX 750
Video Output Device Name=\\.\DISPLAY2
;Audio Friendly Name=Stereo Mix (Realtek High Definition Audio)

When started, the application enumerates (“found video…”, “found audio…”) available video and audio inputs. These discoveries are compared against configuration file settings in order to identify monitor for recording, and possibly audio input device.

Default behavior is to take first available monitor, which happens when settings do not instruct otherwise. By default, no audio is recorded. Audio is recorded and added to resulting file if input device is provided explicitly.

The application also prints which devices are taken for further recording (“using adapter…”).

[Format]
;Video Frame Rate=30000
;Video Frame Rate Denominator=1001
Video Bitrate=4096000
Video Texture Pool Capacity=24
Video Throttle=70
Audio Bitrate=192000

Default behavior is to identify monitor’s refresh rate and produce output file with video at the same frame rate. Video Frame Rate and Video Frame Rate Denominator settings offer an override to target file frame rate. With the former value only, it is the frame rate. With both values they define a ratio, e.g. values of 30000 and 1001 result in 29.97 fps file.

Frame rate reduction is a good way to reduce encoding complexity and overall graphics subsystem load.

Bitrate values define respective bitrates for the encoded content.

Details

As recording goes, the application grabs new desktop snapshots and sends them to encoder. There are no specific expectations about frame rate stability and reduction in case of overload of graphics subsystem. When the complexity is excessive, it is expected that some frames might be lost without breaking the entire playability of the output file.

The application provides additional information when it creates a file, for example:

Using Direct3D 11 at feature level D3D_FEATURE_LEVEL_11_0
Using Desktop Duplication mode: Resolution 1680 x 1050, Refresh Rate 59954/1000, Format DXGI_FORMAT_B8G8R8A8_UNORM
Using path “D:\Projects\...\Output\20160707-070707.mp4”
Using video transform Direct3D 11 Aware, Category MFT_CATEGORY_VIDEO_PROCESSOR, Input MFVideoFormat_ARGB32, Output MFVideoFormat_NV12
Using video transform NVIDIA H.264 Encoder MFT, Direct3D 11 Aware, Category MFT_CATEGORY_VIDEO_ENCODER, Input MFVideoFormat_NV12, Output MFVideoFormat_H264
Started writing…
PPP frames written (QQQ frame timeouts, RRR early frame skips, SSS late frame skips)
Stopped writing
Output file size is TTT bytes

When started the application might experience a condition when certain hardware resource is no longer available, e.g. the desktop itself is locked by user. The application will close the file, and attempt to automatically restart recording into new file. The attempts keep going until user explicitly stops recording.

The application does NOT do the following (among things it could):

  • the application is limited to record from one monitor only; to record from two at a time it is possible to start several instances however the produced result will not be synchronized
  • the application does not provide options to record single window image, to cut a section of monitor image or to scale image down
  • the application does not offer choices for video encoders (e.g. there are two or more hardware H.264 encoders), it will always use encoder picked by the system
  • the application only offers bitrate setting for video encoding
  • the application does not provide flexibility in audio encoding settings, it also expects that audio device is available throughout the entire recording session (esp. is not unplugged as recording goes)

References (Informational)

Download links

KB3176938’s Frame Server update visually

  1. M-JPEG and H.264 media types are available again (good)
  2. Nevertheless connected, H.264 video is not processed correctly; new bug or old one? Not clear. Even though it sort of works, in DirectShow it looks broken in another new way (this and not just this), perhaps a collateral damage and maybe never ever fixed…
  3. There is no camera sharing between the applications even though it was the justification for the changes in first place. For now Frame Server is just useless overhead, which adds bad stuff, is polished a bit to do not so much harm, and maybe turns to be good some time later.
    • for the record, the camera works in Skype when it is not consumed elsewhere concurrently

BTW the hack that bypasses FrameServer survived the update and remains in good standing.

DirectShowCaptureCapabilities and MediaFoundationCaptureCapabilities: API version of EnableFrameServerMode state

Both tools now include exact version of the API and also include an export or registry key related to frame server.

Capture Capabilities: API Version and State

mfcore.dll version of 10.0.14393.105 corresponds to Cumulative Update for Windows 10 Version 1607: August 31, 2016 also known as KB3176938 with DirectShow and Media Foundation improvement for Windows 10 Anniversary Update that restores availability of compressed media types.

See:

Enumeration of DirectShow Capture Capabilities (Video and Audio)

Media Foundation Video/Audio Capture Capabilities

Number of streams served by IMFSourceReader interface

It looks confusing that IMFSourceReader interface does not offer a dedicated method to find out the number of streams behind it. There is a IMFMediaSource instance behind the reader, and its streams are available through IMFMediaSource::CreatePresentationDescriptor method and IMFPresentationDescriptor::GetStreamDescriptorCount method call.

I am under impression that source reader’s method just has to be there even though I am not seeing it looking at the list of methods. Okay, there are other methods, namely IMFSourceReader::GetStreamSelection method, which takes either ordinal stream index or an alias as the first argument, then returns MF_E_INVALIDSTREAMNUMBER if you run out of streams. However the problem is that this is associated with an internal exception, and I consider exceptions as exceptional conditions the code should not normally hit. I would expect to have a legal exception-free way to find out the number of streams. I am using debugger that breaks on exception or at least pollutes output log for no reason, I use other tools that intercept and log exceptions as something that needs attention – getting number of streams is nowhere near there.

Internal MF_E_INVALIDSTREAMNUMBER Exception

Even though it is not a real drawback of the API since it is still possible to get the data and the API acts as documented, I still think someone overlooked this and API like this should have have a normal method or argument to request number of streams explicitly. Or I am just not seeing it even though I am trying thoroughly.

Anniversary Webcam Saga: It’s clear who’s guilty, now what to do? (Updated)

As new and new people discover the Windows 10 Anniversary Update breaking changes (expectedly running mad), let’s reiterate the possible solutions:

  1. You don’t like the idea that video sharing service adds latency, and adds man-in-the-middle access/spying over a video feed.
    See #6 below.
  2. You are consuming raw video from camera using one of the uncompressed modes within USB 2.0 bandwidth.
    You are likely to be not affected by the changes.
  3. You are consuming raw video from camera but resolution/rate combination makes it unable to capture raw video, so you captured M-JPEG instead and decoded that, via DirectShow API.
    It is no longer possible, but you can use Media Foundation API instead. Or someone will develop a wrapper that re-exposes Media Foundation captured video via DirectShow.
  4. Same as #3 above but via Media Foundation API.
    You have the option to consume already decoded video, new subsystem will automatically capture M-JPEG and decode into NV12.
  5. You take advantage of compressed format of video captured (DirectShow or Media Foundation) so that you don’t need compress it for storage or network transmission purposes.
    Compressed captured video is no longer available, see #6 below.
  6. You take advantage of H.264 video capture offered by UVC 1.5 device, including fine tuning of hardware H.264 compression.
    Just as in #1 and #5 above, you are in trouble. Windows Camera Frame Server no longer offers access to such video feed. You need a hack (yes, it’s confirmed to be possible) that restores original behavior of video capture hardware.

These and other reasons related to the fact that applications no longer talk to real capture device, but rather a Frame Server Client that proxies a web camera, will possibly require that video capture applications are updated in order to work well in new version of the operating system.

It is unclear if and how Microsoft and Media Foundation team will respond to customer pain voices. First, it looked as a bug and one could expect a response and fix. But with the information from Windows Camera Team it looks completely different. No, they did not accidentally break it up – it was a planned change. Then they connected new behavior with new Microsoft Products – new products rely on new behavior. Then they did a few nasty things, not just one: added proxy service, killed UVC related compression control over the device, reduced range of operation modes for DirectShow they look for ways to deprecate, conceptually removed compressed video capture modes. I think there is no way back – Windows Camera Frame Server is new reality. The best to expect is that some of the mentioned problems are relaxed by offering greater flexibility by the platform. Maybe they will add some sort of exclusive modes for video capture or “professional” hardware which offers more through the API. In any event these changes are unlikely to appear soon, as they will go through the full cycle of development and take months to get delivered. Public pressure might force that to appear rather earlier than later, but I don’t think it is what is going to happen.

16 Aug update: Windows Camera Team reported that they see customer pain and will do something to ease it shortly. As I see it, they will address scenarios #3, #4, #5 above, for MJPG video, to allow compressed formats pass Frame Server so that users could consume them from their applications and Frame Server would be able to release frames not just after decoder, but also before the shared decoder. Also as use of H.264 is limited, it might be not included into hotfix at all, or will be included much later being given more serious consideration (which might end up as dropped support in DirectShow and something new introduced for Media Foundation).

19 Aug update: Someone took time to locate a registry value. User WithinRafael on MSDN Forums:

Try opening up

HKLM\SOFTWARE\Microsoft\Windows Media Foundation\Platform (32- and 64-bit OS)
HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows Media Foundation\Platform (64-bit OS)

and add a DWORD value with name EnableFrameServerMode. Set its value to 0 and try again.

Put a sticky note on your monitor to revisit this if/when Microsoft issues a fix.

Also:

Untitled