Windows media foundation platform

About Media Foundation

Microsoft Media Foundation is the next generation multimedia platform for Windows that enables developers, consumers, and content providers to embrace the new wave of premium content with enhanced robustness, unparalleled quality, and seamless interoperability.

Media Foundation requires Windows Vista or later. It uses the component object model (COM) and requires C/C++. Microsoft does not provide a managed API for Media Foundation.

The Media Foundation APIs are part of the Windows SDK. To develop a Media Foundation application, install the latest version of the Windows SDK.

Audio and Video Quality

Media Foundation has been designed to meet the challenges posed by high-definition content. Audio and video quality enhancements made throughout the platform now make it possible to deliver a great experience for next generation high-definition content.

DirectX Video Acceleration (DXVA) 2.0 offers more efficient video acceleration, compared with DXVA 1.0, with more robust and streamlined video decoding and extended use of hardware in video processing. With DXVA 2.0, Windows can handle some of the most demanding high-definition content with high quality and improved glitch-resilience.

Color-space information is preserved throughout the video pipeline. Users can enjoy video content with full fidelity. Color information and interlaced images are now passed to hardware for single-pass compositions. Preserving color-space information also reduces unnecessary color space conversions, which frees more cycles to process demanding HD content.

The enhanced video renderer (EVR) offers better timing support, enhanced video processing, and improved glitch-resilience. Full-screen playback support has been enhanced, and video tearing in windowed mode has been minimized.

Media Foundation uses the Multimedia Class Scheduler Service (MMCSS), a new system service in Windows Vista. MMCSS enables multimedia applications to ensure that their time-sensitive processing receives prioritized access to CPU resources.

Content Access

As digital entertainment moves into the high-definition era and content becomes more portable and ubiquitous, content protection will become an integral part of digital media products. The extensibility of Media Foundation ensures that it can support these trends.

In addition, Media Foundation extensibility enables different content protection systems to operate together.

About Media Foundation

This section contains general information about the Media Foundation APIs. Detailed programming information can be found in the Media Foundation Programming Guide.

Section Description
What’s New for Media Foundation Describes new features in Media Foundation.
Media Foundation Headers and Libraries Lists the header and library files that define the Media Foundation APIs.
Media Foundation Tools Describes the development tools that are available for Media Foundation.

Media Foundation is not included with the N and KN editions of WindowsВ 8. For more information, see Microsoft Windows Media Feature Pack for N and KN Versions of all Windows 8 Editions.

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:

Как установить Windows Media Foundation или MFREADWRITE.DLL отсутствует

Как установить Windows Media Foundation

После выхода второго патча весрии (1.0.335.1) для GTA 5 на PC, для игры теперь не обязательно требуется устанавливать Windows Media Player, но Windows Media Foundation должен быть установлен.

У большей части пользователей Windows Media Foundation уже установлен по умолчанию, но в случае если у вас появляется ошибка “Файл MFREADWRITE.DLL отсутствует. Переустановите игру.“.

Вопрос: Мне все время выдает ошибку «Подключение MFREADWRITE.DLL отсутствует, необходимо переустановить игру» (Dependency MFREADWRITE.DLL is missing. Please reinstall the game) при запуске GTAV для ПК, даже если я недавно уже переустановливал игру. Как я могу исправить эту проблему?

Ответ: Эта ошибка обычно появляется, когда вы используете операционную систему Windows 8 N или Windows 8 KN. Они не включают некоторые мультимедийные функции, необходимые для запуска игры. Для установки необходимых мультимедийных функций, пройдите по ссылке ниже и выберете файлы для конкретной операционной системы. После завершения установки ошибка больше не будет появляться.

Чтобы исправить эту ошибку, перейдите по ссылкам на официальный сайт Microsoft, и скачайте Media Feature Pack и данная ошибка исчезнет:

  • Для Windows 8 N/KN
  • Для Windows 8.1 N/KN
  • Для Windows 8.1 Update N/KN

Media Foundation Headers and Libraries

This topic lists the headers and libraries that define all of the Media Foundation APIs.

To find the header and library for a specific API element, consult the reference pages in the Media Foundation Programming Reference.

Headers

  • codecapi.h
  • d3d11.h
  • d3d9.h
  • d3d9caps.h
  • d3d9types.h
  • dxva.h
  • dxva2api.h
  • dxvahd.h
  • evr.h
  • evr9.h
  • mfapi.h
  • mfcaptureengine.h
  • mferrors.h
  • mfidl.h
  • mfmediacapture.h
  • mfmediaengine.h
  • mfmp2dlna.h
  • mfobjects.h
  • mfplat.lib
  • mfplay.h
  • mfreadwrite.h
  • mftransform.h
  • opmapi.h
  • wmcodecdsp.h
  • wmcontainer.h

Libraries

  • dxva2.lib
  • evr.lib
  • mf.lib
  • mfplat.lib
  • mfplay.lib
  • mfreadwrite.lib
  • mfuuid.lib

Library Changes in Windows 7

Starting in WindowsВ 7, certain Media Foundation functions are exported from different DLL files than previous versions.

These changes affect the following .lib files:

An application that uses any of these functions must link to a different set of .lib files, depending on the SDK version and the target platform.

SDK Version Libraries
Windows SDK for WindowsВ Vista
Windows SDK for Windows ServerВ 2008
evr.lib
mf.lib
mfplat.lib
Windows SDK for WindowsВ 7 If the target platform is WindowsВ Vista or Windows ServerВ 2008, link the following libraries:
  • evr_vista.lib
  • mf_vista.lib
  • mfplat_vista.lib

If the target platform is WindowsВ 7 or later, link the following libraries:

  • evr.lib
  • mf.lib
  • mfplat.lib

Additional Info on Helper Functions

The WindowsВ 8 MFPlat.dll is a component of the MicrosoftВ Windows operating system. It has several functions included in the module.

MFPlat implements helper functionality for low level memory allocation, operation scheduling FIFOs, and win32 file access abstractions. To be more specific, it provides support for the following:

  • allocating and initializing memory buffers (known as ‘samples’) and helpers to simplify managing their lifetimes
  • efficient Data copying functions for memory buffers
  • allocating and initializing operation FIFOs (known as ‘events’)
  • implementing a simple clock object
  • implementing a win32 file wrapper
  • allocating and initializing arrays of memory buffers for CPUs and GPUs

If the MFStartup method succeeds, MFPlat provides the following work queue functionality:

  • internally supporting I/O items (as used by the win32 file wrapper and socket libraries)
  • providing an array of multithreaded work queues with thread priority support
  • supporting work items, timer items, and wait items through the work queues

MFPlat provides helper functionality for finding and creating media transforms and media sources registered on the system, and creating and manipulating media types, though MFPlat itself cannot create the actual media nor play it back.

Пошаговое руководство. Создание приложения UWP с использованием WRL и Media Foundation Walkthrough: Creating a UWP app using WRL and Media Foundation

Для новых приложений и компонентов UWP рекомендуется использовать c++/WinRT— новую стандартную проекцию c++ 17 для Среда выполнения Windows API. For new UWP apps and components, we recommend that you use C++/WinRT, a new standard C++17 language projection for Windows Runtime APIs. C++/WinRT доступна в пакете SDK для Windows 10, начиная с версии 1803. C++/WinRT is available in the Windows 10 SDK from version 1803 onward. C++/WinRT реализована полностью в файлах заголовков и предназначена для предоставления доступа к современным API Windows через первый класс. C++/WinRT is implemented entirely in header files, and is designed to provide you with first-class access to the modern Windows API.

В этом руководстве вы узнаете, как использовать библиотеку шаблонов C++ среда выполнения Windows (WRL) для создания приложения универсальная платформа Windows (UWP), использующего Microsoft Media Foundation. In this tutorial, you’ll learn how to use the Windows Runtime C++ Template Library (WRL) to create a Universal Windows Platform (UWP) app that uses Microsoft Media Foundation.

В этом примере создается настраиваемое преобразование Media Foundation. This example creates a custom Media Foundation transform. Он применяет к изображениям, захваченным с веб-камеры, эффекты в градациях серого. It applies a grayscale effect to images that are captured from a webcam. Приложение использует C++ для определения пользовательского преобразования и C# для использования компонента и выполнения преобразования захваченного изображения. The app uses C++ to define the custom transform and C# to use the component to transform the captured images.

Чтобы воспользоваться пользовательским компонентом преобразования вместо C# можно также использовать JavaScript, Visual Basic или C++. Instead of C#, you can also use JavaScript, Visual Basic, or C++ to consume the custom transform component.

Для создания среда выполнения Windows компонентов обычно можно использовать C++/CX. You can usually use C++/CX to create Windows Runtime components. Однако иногда необходимо использовать WRL. However, sometimes you have to use the WRL. Например, при создании расширения мультимедиа для Microsoft Media Foundation необходимо создать компонент, реализующий интерфейсы COM и среда выполнения Windows. For example, when you create a media extension for Microsoft Media Foundation, you must create a component that implements both COM and Windows Runtime interfaces. Так как C++/CX может создавать только объекты среда выполнения Windows, для создания расширения мультимедиа необходимо использовать WRL. Because C++/CX can only create Windows Runtime objects, to create a media extension you must use the WRL. Это обусловлено тем, что позволяет реализовать интерфейсы COM и среда выполнения Windows. That’s because it enables the implementation of both COM and Windows Runtime interfaces.

Хотя этот пример кода является объемным, он показывает минимум, необходимый для создания полезных преобразований Media Foundation. Although this code example is long, it demonstrates the minimum that’s required to create a useful Media Foundation transform. Его можно использовать в качестве отправной точки для собственного пользовательского преобразования. You can use it as a starting point for your own custom transform. Этот пример адаптируется из примера расширений мультимедиа, в котором используются расширения мультимедиа для применения эффектов к видео, расшифровки видео и создания обработчиков схем, создающих потоки мультимедиа. This example is adapted from the Media extensions sample, which uses media extensions to apply effects to video, decode video, and create scheme handlers that produce media streams.

Предварительные требования Prerequisites

В Visual Studio 2017 и более поздних версиях поддержка UWP является дополнительным компонентом. In Visual Studio 2017 and later, UWP support is an optional component. Чтобы установить его, откройте Visual Studio Installer из меню «Пуск» Windows и найдите свою версию Visual Studio. To install it, open the Visual Studio Installer from the Windows Start menu and find your version of Visual Studio. Выберите изменить и убедитесь, что выбран элемент Разработка универсальная платформа Windows . Choose Modify and then make sure the Universal Windows Platform Development tile is checked. В разделе необязательные компоненты проверьте инструменты c++ для UWP (V141) для Visual Studio 2017 или инструменты c++ для UWP (v142) для Visual Studio 2019. Under Optional Components check C++ Tools for UWP (v141) for Visual Studio 2017, or C++ Tools for UWP (v142) for Visual Studio 2019. Затем проверьте версию Windows SDK, которую вы хотите использовать. Then check the version of the Windows SDK that you want to use.

опыт работы с моделью COM; Experience with COM.

Веб-камера, A webcam.

Ключевые моменты Key points

Для создания пользовательского компонента Media Foundation используйте файл определения языка MIDL, чтобы определить и реализовать интерфейс, а затем сделать его активируемым из других компонентов. To create a custom Media Foundation component, use a Microsoft Interface Definition Language (MIDL) definition file to define an interface, implement that interface, and then make it activatable from other components.

namespace Атрибуты и runtimeclass , а также NTDDI_WIN8 значение атрибута Version являются важными частями определения MIDL для Media Foundation компонента, использующего WRL. The namespace and runtimeclass attributes, and the NTDDI_WIN8 version attribute value are important parts of the MIDL definition for a Media Foundation component that uses WRL.

Microsoft::WRL::RuntimeClass является базовым классом для пользовательского компонента Media Foundation. Microsoft::WRL::RuntimeClass is the base class for the custom Media Foundation component. Microsoft::WRL::RuntimeClassType::WinRtClassicComMix] Значение перечисления [(runtimeclasstype-Enumeration.md), которое указывается в качестве аргумента шаблона, помечает класс для использования в качестве класса среда выполнения Windows и классического класса среды выполнения COM. The [ Microsoft::WRL::RuntimeClassType::WinRtClassicComMix] (runtimeclasstype-enumeration.md) enum value, which is provided as a template argument, marks the class for use both as a Windows Runtime class and as a classic COM runtime class.

InspectableClass Макрос реализует базовые функциональные возможности com, такие как подсчет ссылок и QueryInterface метод, и задает имя класса среды выполнения и уровень доверия. The InspectableClass macro implements basic COM functionality such as reference counting and the QueryInterface method, and sets the runtime class name and trust level.

Используйте Microsoft::WRL::Module класс для реализации функций точки входа DLL, таких как DllGetActivationFactory , DllCanUnloadNow и DllGetClassObject . Use the Microsoft::WRL::Module class to implement DLL entry-point functions such as DllGetActivationFactory , DllCanUnloadNow , and DllGetClassObject .

Свяжите библиотеку DLL компонента с runtimeobject.lib . Link your component DLL to runtimeobject.lib . Также укажите /WINMD в строке компоновщика, чтобы создать метаданные Windows. Also specify /WINMD on the linker line to generate Windows metadata.

Используйте ссылки проекта, чтобы сделать компоненты WRL доступными для приложений UWP. Use project references to make WRL components accessible to UWP apps.

Использование WRL для создания компонента преобразования в градациях серого Media Foundation To use the WRL to create the Media Foundation grayscale transform component

В Visual Studio создайте пустой проект решения . In Visual Studio, create a Blank Solution project. Присвойте проекту имя, например медиакаптуре. Name the project, for example, MediaCapture.

Добавьте в решение проект DLL (универсальный Windows) . Add a DLL (Universal Windows) project to the solution. Присвойте проекту имя, например грайскалетрансформ. Name the project, for example, GrayscaleTransform.

Добавьте в проект файл MIDL (. IDL) . Add a MIDL File (.idl) file to the project. Присвойте файлу имя, например GrayscaleTransform.idl . Name the file, for example, GrayscaleTransform.idl .

Добавьте следующий код в Грайскалетрансформ. IDL: Add this code to GrayscaleTransform.idl:

Используйте следующий код, чтобы заменить содержимое pch.h : Use the following code to replace the contents of pch.h :

Добавьте новый файл заголовка в проект, присвойте ему имя BufferLock.h , а затем замените содержимое следующим кодом: Add a new header file to the project, name it BufferLock.h , and then replace the contents with this code:

GrayscaleTransform.h не используется в этом примере. GrayscaleTransform.h isn’t used in this example. Его можно удалить из проекта при необходимости. You can remove it from the project if you want to.

Используйте следующий код, чтобы заменить содержимое GrayscaleTransform.cpp : Use the following code to replace the contents of GrayscaleTransform.cpp :

Добавьте новый файл определения модуля в проект, присвойте ему имя GrayscaleTransform.def , а затем добавьте следующий код: Add a new module-definition file to the project, name it GrayscaleTransform.def , and then add this code:

Используйте следующий код, чтобы заменить содержимое dllmain.cpp : Use the following code to replace the contents of dllmain.cpp :

В диалоговом окне страницы свойств проекта задайте следующие свойства компоновщика . In the project’s Property Pages dialog box, set the following Linker properties.

В разделе входные данные для файла определения модуля укажите GrayScaleTransform.def . Under Input, for the Module Definition File, specify GrayScaleTransform.def .

Кроме того, в разделе входные данные добавьте runtimeobject.lib , mfuuid.lib и mfplat.lib в свойство Дополнительные зависимости . Also under Input, add runtimeobject.lib , mfuuid.lib , and mfplat.lib to the Additional Dependencies property.

В разделе метаданные Windows задайте для параметра создать метаданные Windows значение Да (/WinMD). Under Windows Metadata, set Generate Windows Metadata to Yes (/WINMD).

Использование WRL компонента пользовательского Media Foundation из приложения C# To use the WRL the custom Media Foundation component from a C# app

Добавьте в решение новый проект пустое приложение C# (универсальный Windows) MediaCapture . Add a new C# Blank App (Universal Windows) project to the MediaCapture solution. Присвойте проекту имя, например медиакаптуре. Name the project, for example, MediaCapture.

В проекте медиакаптуре добавьте ссылку на GrayscaleTransform проект. In the MediaCapture project, add a reference to the GrayscaleTransform project. Дополнительные сведения см. в разделе как добавить или удалить ссылки с помощью диспетчера ссылок. To learn how, see How to: Add or remove references by using the reference manager.

В Package.appxmanifest на вкладке возможности выберите микрофон и веб-камера. In Package.appxmanifest , on the Capabilities tab, select Microphone and Webcam. Обе возможности необходимы для получения фотографий с веб-камеры. Both capabilities are required to capture photos from the webcam.

В MainPage.xaml добавьте следующий код в корневой Grid элемент: In MainPage.xaml , add this code to the root Grid element:

Используйте следующий код, чтобы заменить содержимое MainPage.xaml.cs : Use the following code to replace the contents of MainPage.xaml.cs :

На следующем рисунке показан MediaCapture app . The following illustration shows the MediaCapture app .

Next Steps Next Steps

Пример показывает способ записи фотографий (по одной) с веб-камеры по умолчанию. The example shows how to capture photos from the default webcam one at a time. Пример расширений мультимедиа выполняет больше возможностей. The Media extensions sample does more. Здесь показано, как перечислять видеокамеры и работать с локальными обработчиками схем. It demonstrates how to enumerate webcam devices and work with local scheme handlers. В этом примере также демонстрируются другие эффекты мультимедиа, которые работают как с отдельными фотографиями, так и с потоками видео. The sample also demonstrates other media effects that work on both individual photos and streams of video.

Читайте также:  Windows 10 запретить режим планшета
Оцените статью