Windows media foundation net

What’s New for Media Foundation

Microsoft Media Foundation was introduced in WindowsВ Vista as the replacement for DirectShow. Of course, DirectShow is still supported in WindowsВ 7, but developers are encouraged to use Media Foundation in their new digital media applications.

The improvements to Media Foundation can be summarized as follows:

  • Better format support, including MPEG-4
  • Support for capture devices and hardware codecs
  • A simplified programming model
  • Improvements to the platform

Better Format Support

The Media Foundation audio/video pipeline was implemented in WindowsВ Vista, but it supported a limited set of formats and file containers, which meant that some applications needed to fall back on older technologies such as DirectShow. In WindowsВ 7, Media Foundation includes the following new codecs, media sources, and media sinks:

  • AAC decoder
  • AAC encoder
  • AVI/WAVE file source
  • DV video decoder
  • H.264 video decoder
  • H.264 video encoder
  • MJPEG decoder
  • MP3 file sink*
  • MP4/3GP file source
  • MP4/3GP file sink

The MP3 file sink does not include an MP3 audio encoder.

Hardware Device Support

Media Foundation now supports the following types of hardware devices in the audio/video pipeline:

  • UVC 1.1 video capture devices, such as webcams
  • Audio capture devices
  • Hardware encoders and decoders
  • Hardware video processors, such as color-space converters

Hardware codecs can perform very fast video transcoding. For example, an application might transfer Windows Media Video (WMV) files to a cell phone that supports only 3GP files. Using a hardware encoder, the application can transcode the file in the backgound, just before transferring it to the device.

Hardware devices are represented in Media Foundation by a proxy object, and are used in the pipeline just like software-based components.

Simplified Programming Model

In WindowsВ Vista, Media Foundation exposed a relatively low-level set of APIs. These APIs are flexible, but too complex for simple tasks. WindowsВ 7 adds new high-level APIs that make it simpler to write media applications in C++. These new high-level APIs include the following.

API Description
Source Reader The source reader pulls raw or decoded data from a media file. For example, you can use the source reader to get thumbnail bitmaps from a video file, or to analyze the waveform data in an audio file. You can also use the source reader to get live data from an audio or video capture device.
Sink Writer The sink writer enables you to author media files by passing in uncompressed or encoded data. For example, you can use it to re-encode a video file, or to capture live video from a webcam to a file.
Transcode API This feature supports the most common audio/video encoding scenarios.

You can still use the low-level APIs in Media Foundation. You might do so if you need more control over the audio/video pipeline.

Platform Improvements

WindowsВ 7 includes numerous enhancements to the underlying Media Foundation platform APIs. Advanced applications can use these APIs directly; other applications will get the benefits indirectly. The improvements include:

  • Changes in the video pipeline to reduce power consumption and video memory usage.
  • DXVA-HD: Microsoft DirectX Video Acceleration High Definition (DXVA-HD) is a new API for hardware-accelerated video processing. DXVA-HD offers a more flexible compositing model than the previous DXVA video processing API, and is better suited for high-definition video formats..
  • A new mechanism for enumerating sources and decoders, which includes merit values and a preferred/blocked list. This feature improves the overall reliability of the system. For more information, see the following topics:
    • MFTEnumEx
    • IMFPluginControl
    • Codec Merit

SDK Changes

  • New headers and library files: Media Foundation Headers and Libraries
  • DLL and .lib changes: Library Changes in WindowsВ 7
  • New SDK Samples:
    • Audio Clip Sample
    • DXVA-HD Sample
    • MFCaptureD3D Sample
    • MFCaptureToFile Sample
    • Transcode Sample
    • VideoThumbnail Sample
  • Improvements to TopoEdit:
    • Support for transcoding. See Building a Transcode Topology with TopoEdit.
    • Support for audio and video capture. See Topology Menu.

New in Windows 8

Some of the new updates to Media Foundation with WindowsВ 8 are:

How to Play Media Files with Media Foundation

This tutorial shows how to play media files using the Media Session object.

Prerequisites

Before reading this topic, you should be familiar with the following Media Foundation concepts:

This topic does not describe how to play files that are protected by digital rights management (DRM). For information about DRM in Microsoft Media Foundation, see How to Play Protected Media Files.

Overview

The following objects are used to play a media file with the Media Session:

  • A media source is an object that parses a media file or other source of media data. The media source creates stream objects for each audio or video stream in the file. Decoders convert encoded media data into uncompressed video and audio.
  • The Source Resolver creates a media source from a URL.
  • The Enhanced Video Renderer (EVR) renders video to the screen.
  • The Streaming Audio Renderer (SAR) renders audio to a speaker or other audio output device.
  • A topology defines the flow of data from the media source to the EVR and SAR.
  • The Media Session controls the data flow and sends status events to the application. The following diagram illustrates this process.

The following is a general outline of the steps needed to play a media file using the Media Session:

Call the MFStartup function to initialize the Media Foundation platform.

Call MFCreateMediaSession to create a new instance of the Media Session.

Use the source resolver to create a media source. For more information, see Using the Source Resolver.

Create a topology that connects the media source to the EVR and SAR. In this step, the application creates a partial topology that does not include the decoders. For more information, see Creating Playback Topologies.

Call IMFMediaSession::SetTopology to set the topology on the Media Session.

Use the IMFMediaEventGenerator interface to get events from the Media Session.

When the application exits, release resources:

  1. Call IMFMediaSession::Close to close the Media Session. This method is asynchronous. When it completes, the Media Session sends an MESessionClosed event. Then it is safe to perform the remaining steps.
  2. Call IMFMediaSource::Shutdown to shut down the media source.
  3. Call IMFMediaSession::Shutdown to shut down the Media Session.
  4. Call MFShutdown to shut down the Media Foundation platform.

The following sections show a complete code example:

Media Foundation

Media Foundation (сокращается до MF) — мультимедийный фреймворк и интерфейс программирования приложений нового поколения, созданный корпорацией Microsoft для работы с цифровым мультимедиа под операционными системами семейства Windows, начиная с Vista. Согласно планам Microsoft, он заменит DirectShow, Windows Media SDK, DirectX Media Objects (DMOs) и более старые мультимедийные API, такие, как Audio Compression Manager (ACM) и Video for Windows (VfW). При этом в течение некоторого времени предполагается параллельное сосуществование DirectShow и Media Foundation. В Windows XP и более старых операционных системах использование MF не планируется.

В первом релизе Media Foundation, выпущенном с Windows Vista, основное внимание уделено качеству воспроизведения аудио и видео, контенту высокой чёткости (то есть, ТВЧ), защите контента, более унифицированному подходу к контролю доступа к цифровым данным для средств защиты авторских прав (DRM) и их взаимодействию.

Содержание

Архитектура

Архитектура MF подразделяется на слой управления (Control layer), слой ядра (Core layer) и слой платформы (Platform layer). Слой ядра включает большую часть функциональности Media Foundation. Он является мультимедийным конвейером, состоящим из трёх частей: Media Source (объект-«источник» мультимедиа данных), Media Sink (объект-«приёмник» обработанных данных) и Media Foundation Transforms (MFT).

Media Foundation Transforms

Media Foundation Transforms получает от Media Source данные, производит промежуточную обработку и отдаёт объекту Media Sink. Он может состоять из нескольких обрабатывающих фильтров, а может быть и пустым. Эти фильтры могут идти последовательно, образуя мультимедийный конвейер (pipeline), а могут и независимо друг от друга. Примеры фильтров MFT:

  • Аудио- и видеокодеки
  • Аудио- и видеоэффекты
  • Мультиплексоры и демультиплексоры
  • Разветвители
  • Преобразователи цветового пространства
  • Преобразователи частоты
  • Преобразователи размера видео

Для Windows Vista Microsoft рекомендует разработчикам писать фильтры MFT вместо DirectShow [1] .

Enhanced Video Renderer

В MF включён новый видео рендерер, Enhanced Video Renderer (EVR), который является следующим поколением рендереров в ряду VMR 7 и 9. В Media Foundation EVR выступает в качестве объекта Media Sink (объекта-приёмника), при этом он может смешивать до 16 параллельных потоков, один из которых является референсным. Все потоки, кроме референсного, могут содержать информацию о прозрачности каждого своего пикселя и информацию о порядке наложения. Референсный поток не имеет прозрачных пикселей и всегда находится в самом низу порядка наложения. Результирующее изображение создаётся путём окраски каждого пикселя согласно цвету и прозрачности соответствующих пикселей всех потоков.

Преимущества над DirectShow

MF обладает следующими преимуществами:

  • Масштабируемость для высокоразмерного контента и контента, защищённого DRM.
  • Позволяет использовать DirectX-акселерацию видео без использования инфраструктуры DirectShow. DXVA 2.0 может быть доступен для компонент пользователя без использования видео рендерера DirectShow.
  • Media Foundation позволяет совместно работать различным системам защиты контента.
  • Media Foundation использует Multimedia Class Scheduler Service (MMCSS, англ.), новую службу, которая выставляет воспроизведению мультимедиа приоритет реального времени для резервирования требуемых при воспроизведения ресурсов. MMCSS гарантирует мультимедийным приложениям приоритетный доступ к ресурсам ЦП, который обеспечивает более точное по времени воспроизведение мультимедиа.

Media Foundation сопутствует двум другим технологиям — Direct3D 10 и Windows Presentation Foundation, идя в ногу с эволюцией графики и мультимедийного аппаратного обеспечения и требованиями мультимедийных приложений.

Использование в приложениях

Сейчас Media Foundation используется главным образом в службах и сервисах Windows:

  • Windows Protected Media Path (PMP), полностью основан на Media Foundation.
  • Windows Media Player в Windows Vista использует Media Foundation для воспроизведения формата ASF (WMA и WMV) и защищённого контента, но вместо этого также может использовать DirectShow или Windows Media Format SDK. В случае воспроизведения WMV9, также используется DXVA 2.0 вместо DXVA 1.0, если поддерживается аппаратное декодирование WMV9/VC-1.
  • DirectX Video Acceleration (DXVA) 2.0, конвейер аппаратной акселерации видео в Windows Vista, также основан на Media Foundation.

Windows media foundation net

Repository for Windows Media Foundation related tools and samples

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

What is this repo?

A collection of Microsoft Media Foundation sample apps along with tooling and documentation. Our goal is to share code samples, documentation, our favorite tools, and tips and tricks for troubleshooting Media Foundation issues.

  • MediaEngineUWP — A sample UWP C++/WinRT application which demonstrates media playback using the MediaFoundation MediaEngine API and the WinRT composition APIs.
  • MediaEngineEMEUWP — A sample UWP application written in C++ which demonstrates protected Playready EME media playback using the MediaFoundation MediaEngine API and the WinRT composition APIs.
  • MediaEngineDCompWin32Sample — A sample native C++ Win32 application which demonstrates media playback using the MediaFoundation MediaEngine API and the DirectComposition API.

Tracing and Debugging

Media Experience Analyzer (MXA) — An advanced analysis tool used by Media experts to analyze Media Foundation performance traces.

  • Available for download packaged with the Windows ADK here. You can opt to install only MXA using the installer.
  • Microsofts Channel9 has produced a series of training videos for MXA available here

GPUView — A development tool for determining the performance of the graphics processing unit (GPU) and CPU. It looks at performance with regard to direct memory access (DMA) buffer processing and all other video processing on the video hardware.

TopoEdit — A visual tool for building and testing Media Foundation topologies.

Other useful links

We’re always looking for your help to fix bugs and improve the samples. Create a pull request, and we’ll be happy to take a look.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

About

Repository for Windows Media Foundation related tools and samples

Читайте также:  Samsung зависает при установке windows
Оцените статью