Skip to content

MfPack Methods Library Index

FactoryX edited this page Nov 8, 2025 · 23 revisions

The MfPack Methods Library (WinApi.MediaFoundationApi.MfMetLib.pas) contains lots of methods to be used with Media Foundation.

Structures

TMFAudioFormat Record that holds all audioformat parameters.

TVideoFormatInfo Used by TDeviceProperties, holding capabillities of a video capture device.

TDeviceProperties Used in arrays to hold capture device enum data.

TStreamContents Audio and video stream contents.

Enumerations

TMediaTypes Stream indentifiers

Arrays

TMFAudioFormatArray Array that holds audio data (TMFAudioFormat records)

TVideoFormatInfoArray Array that holds retrieved capabillities records (TVideoFormatInfo records)

TDevicePropertiesArray Array that holds retrieved devices by name and/or index. (TDeviceProperties records)

TStreamContentsArray Array that holds retrieved audio and video stream contents (TStreamContents records)

Methods

Collections

function GetCollectionObject Gets an interface pointer from a Media Foundation collection.

Events

function GetEventObject Gets an object from a media event interface (IMFMediaEvent).

procedure HandleMessages Alternative for ProcessMessages.

Media Samples

function CreateMediaSample Create a sample (IMFSample) and add a buffer to it.

Media Source

function CreateObjectFromUrl Create a media object from an URL or stream.

function CreateMediaSourceFromUrl Create a media object from an URL (deprecated, use CreateMediaSourceFromUrl)

function CreateObjectFromUrlAsync Begins an asynchronous request to create a media source or a byte stream from an URL.

function CreateAggregatedSource The aggregated media source is useful for combining streams from separate media sources. For example, you can use it to combine a video capture source and an audio capture source.

function CreateVideoDeviceSource Create a media source for the given device ID. Note: The application have to enumerate the device first.

Sink- and Sourcereaders

function CreateReaderWriter Creates a sourcereader or sinkwriter depending on the given CLSID.

function CreateVideoMediaSinkActivate Returns a video activation object that is able to render to a window or any other visual component that has a THandle (HWND).

function CreateAudioMediaSinkActivate Returns an audio activation object for a renderer.

function SetSafeStream Deselects all IMFSourceReader streams, and sets the proper stream to prevent error $8007000E (E_OUT_OF_MEMORY).

Topologies

function CreatePlaybackTopology Creates a playback topology from the media source. Pre-condition: The media source must be created already. - Call CreateMediaSourceFromUrl() or CreateMediaSourceFromUrlAsync() before calling this method. - Create a playback topology from a media source.

function AddBranchToPartialTopology Adds a topology branch for one stream. Notes: For each stream, we must do the following: 1. Create a source node associated with the stream. 2. Create an output node for the renderer. 3. Connect the two nodes. The media session will resolve the topology, so we do not have to worry about decoders or other transforms.

function AddBranchToPartialTopologyWithDecoder Create the nodes and connect them. This function is very similar to the function named AddBranchToPartialTopology (Creates a playback topology). The only difference is that this function adds the extra node for the decoder.

function GetPresentationDescriptorFromTopology Given a topology, returns a pointer to the presentation descriptor.

function GetDurationFromTopology Returns the duration from a topology.

Source nodes

function AddSourceNode Creates and initializes a source node from a MediaSource.

function AddSourceStreamNode Creates and initializes a source node from a MediaSource.

Output nodes

function AddOutputNodeA Creates and initializes an output node from an activation object.

function AddOutputNodeS Creates and initializes an output node from a stream sink.

function CreateOutputNode Creates an uotput node from a stream descriptor (IMFStreamDescriptor).

Transform nodes

function AddTransformNodeM Creates and initializes a transform node from an MFT (IMFTransform).

function AddTransformNodeC Creates and initializes a transform node from a CLSID.

function AddTransformNodeA Creates and initializes a transform node from an activation object (IMFActivate).

Seeking & Rate

function DoScrub Scrub given a period (MFTime).

function SetPlaybackRate Set the playback rate within a mediasession (IMFMediaSession).

Sessions

function SetMediaStop Sets the Stop Time Before Playback begins.

function SetMediaStopDynamic Sets the stop time AFTER playback has started.

De- & Encoders

function FindDecoderEx This function searches for a video or audio decoder. Asynchronous, hardware, transcode, and field-of-use decoders are excluded. If a match is found, the code creates the first MFT in the list. This function is superseded by function GetCodec.

function FindEncoderEx Searches for a video or audio encoder. Asynchronous, hardware, transcode, and field-of-use encoders are excluded. This function is superseded by function GetCodec.

function FindVideoDecoder Searches for a video decoder, with options to include asynchronous, hardware or transcode decoders. This function is superseded by function GetCodec.

function GetDecoderCategory Returns the MFT decoder based on the major type GUID.

function EnumMft Enumerates mft's by category and returns an array of IMFActivate pointers.

function GetMftEnumInfo Find the in- and outputs of a MFTclsid (for example CLSID_CMSH264EncoderMFT).

function GetCodec Searches for a codec (encoder or decoder), with options to include asynchronous, hardware, or transcode decoders, majortype and category. See: MFT_ENUM_FLAG For info for parameter mftRegisterTypeInfo.guidMajorType See: Media Type Guids For info for parameter mftRegisterTypeInfo.guidSubtype See: Video Subtype Guids Audio Subtype Guids Valid value for parameter mftCategory: MFT_CATEGORY_VIDEO_ENCODER, MFT_CATEGORY_VIDEO_DECODER, MFT_CATEGORY_AUDIO_ENCODER or MFT_CATEGORY_AUDIO_DECODER. The value for parameter selIndex is 0 by default, which means the function will select the first mft in the list. If you want another fmt, you should call function EnumMft prior to this function to determine the mft from the list.

                 Parameters mftRegisterTypeInput and mftRegisterTypeOutput values can be retrieved by calling function GetMftEnumInfo prior
                 to calling this function. One or both parameters can be nil. If nil, all input or/and output types are matched.

function GetDecoderCategory Returns the MFT decoder based on the major type GUID.

function GetEncoderCategory Returns the MFT encoder based on the major type GUID.

function GetMftCategories Returns an array of MFT guids, guid names and mft descriptions.

function FindDecoderForStream Finds a decoder for a stream. If the stream is not compressed, pCLSID receives the value GUID_NULL.

function ConfigureVideoEncoding Creates a transcode profile for the given params mfAudioFormat and mfTranscodeContainerType.

function ConfigureVideoEncoding Configures the recordsink for video.

function ConfigureAudioEncoding Configures the recordsink for audio (if an audiostream is present).

function SetDeviceFormat Sets the Video Capture Format for a capture device. Pre-condition: - Call method EnumerateCaptureFormats first to inventarize the supported capture formats of the device.

                        To set a capture format:
                        1 - Get a pointer to the IMFMediaTypeHandler interface, as shown under Enumerations / function EnumerateCaptureFormats.
                        2 - Call IMFMediaTypeHandler.GetMediaTypeByIndex to get the desired format, specified by index.
                        3 - Call IMFMediaTypeHandler.SetCurrentMediaType to set the format.

                        If you do not set the capture format, the capturedevice will use its default format.

function ListEncoders List audio or video encoders on this system.

function CreateEncoderFromClsid Create an encoder found with function ListEncoders.

function CreateUncompressedVideoType This function fills in the most common information for an uncompressed video format. The function returns an IMFMediaType interface pointer. You can then add additional attributes to the media type as needed.

function ConvertVideoTypeToUncompressedType This function takes an encoded video format as input, and creates a matching uncompressed video type. This type would be suitable to set on an encoder or decoder.

Enumerations

To enumerate the video capture devices on the system, do the following: Call function EnumCaptureDeviceSources with the following parameters: Parameters: AttributeSourceType: MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID for audio or MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID for video. DeviceProperties: array of TDevicePropsA.

  1. Call MFCreateAttributes to create an attribute store. This function receives an empty IMFAttributes pointer.
  2. Call IMFAttributes.SetGUID to set the MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE attribute. Set the attribute value to MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID.
  3. Call MFEnumDeviceSources. This function receives an array of IMFActivate pointers and the array size. Each pointer represents a distinct video capture device.

To create an instance of a capture device: Call IMFActivate.ActivateObject to get a pointer to the IMFMediaSource interface.

function EnumCaptureDeviceSources This function provide the steps 1 to 3.

function GetCaptureDeviceCaps Retrieves all native video formats of a device and stores them in TDevicePropertiesArray

function GetSupportedVideoFormats Checks if the the formats stored in the TDevicePropertiesArray are supported by Media Foundation.

function CreateCaptureDeviceInstance This function activates a selected device stored in TDeviceProperties.

function EnumerateCaptureFormats Enumerates the capture formats for a device. Note: See also function SetDeviceFormat This function returns an pointer array of IMFMediaType. To get the current capture device's IMFMediaSource object, call IMFCaptureSource.GetCaptureDeviceSource.

function CountTypesFromDevice Counts mediatypes from a device When the list index goes out of bounds, GetNativeMediaType returns MF_E_NO_MORE_TYPES. This is not an error, but indicates the end of the list. Set parameter MfSupportedOnly to False if you want to get the total of all native types from the device and to True for Media Foundation supported formats.

function GetGUIDNameConst Returns the name, name of the formattag and FOURCC value of a guid.

function IsMfSupportedFormat Checks if a given input subtype is supported by Media Foundation MFT. (deprecated)

function IsMftSupportedInputFormat Replaces IsMfSupportedFormat

Device Loss

function RegisterForDeviceNotification Register for Device Notification. Before you start capturing from a device, call function RegisterDeviceNotification to register for device notifications. Register for the KSCATEGORY_CAPTURE device class, as shown in this function.

function UnRegisterForDeviceNotification Before an application or device is closing, unregister for device notifications.

Device SymLink & FriendlyName

function GetSymbolicLink Get the Symbolic Link of the device.

Enumerate the video devices on the system, as described in Enumerating Video Capture Devices. Choose a device from the list, and then query the activation object for the MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK (= default) or MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_SYMBOLIC_LINK attribute, as shown in this function.

function GetDeviceName Get the readable name of the device.

Enable Video Acceleration

Adds an audio or video decoder to a topology (applies only to video decoders). To get the best performance for video playback, you should enable DirectX Video Acceleration (DXVA) if the video decoder supports it. Usually this step is performed by the topology loader, but if you add the decoder to the topology manually, then you must perform this step yourself. As a precondition for this step, all output nodes in the topology must be bound to media sinks. For more information, see Binding Output Nodes to Media Sinks.

First, find the object in the topology that hosts the Direct3D device manager. To do so, get the object pointer from each node and query the object for the IDirect3DDeviceManager9 service. Typically the enhanced video renderer (EVR) serves this role.

The following function shows a function that finds the device manager:

function FindDeviceManager Finds the node in the topology that provides the Direct3D device manager.

Audio and video capture

function CreateVideoCaptureDevice Creates a media source for the choosen deviceindex of the video capture device in the enumeration list.

function CreateAudioCaptureDevice Takes an audio endpoint ID and creates a media source.

procedure ListDeviceNames Lists the devicenames from an IMFActivate array.

function SetMaxFrameRate Sets the maximum frame rate on the media source.

SAR (Streaming Audio Renderer)

function EnumAudioRenderingDevices Enumerates the audio rendering devices and assigns the first device or nDevice in the list to the SAR.

Helper methods

function GetBitmapInfoHeaderFromMFMediaType This function fills in a BITMAPINFOHEADER structure from a video media type. Note that this conversions loses some of the format information (interlacing, frame rate, extended color data). However, it might be useful when saving a bitmap from a video frame, for example. Converts a video type to a BITMAPINFO structure. The caller must free the structure by calling CoTaskMemFree.

function CopyAttribute Copies an attribute value from one attribute store to another.

function CloneVideoMediaType Creates a compatible video format with a different subtype if param guidSubType <> GUID_NULL else the SubType will be the source subtype.

function CreatePhotoMediaType Creates a JPEG, RGB32 or WIC GUID_ContainerFormat imagetype that is compatible with a specified video media type. NOTE: When parameter pSubTypeGuid is wrong or not supported the result value in OnCaptureEvent.MF_CAPTURE_ENGINE_PHOTO_TAKEN will be WINCODEC_ERR_COMPONENTNOTFOUND Valid subformats are: MFImageFormat_JPEG, GUID_ContainerFormatBmp, GUID_ContainerFormatJpeg etc. WARNING: DON'T USE MFImageFormat_RGB32! (This will end with a WINCODEC_ERR_COMPONENTNOTFOUND)

Video Media Type Helpers

function GetFrameRate Helper function to get the frame rate from a video media type.

function SetFrameRate Helper function to set the frame rate on a video media type.

function GetFrameRateFromRatio Helper to calculate framerate from ratio (numerator / denominator).

function GetFrameSize Helper function to get the frame size from IMFAttributes.

function GetFrameSizeFromMediaType Helper function to get the frame size from a video media type.

function SetFrameSize Helper function to set the frame size on a video attributes.

function SetFrameSizeOnMediaType Helper function to set the frame size on a video media type.

function GetEncodingBitrate Helper to get the encoding bitrate from a media type.

function GetPixelAspectRatio Helper function to get the pixel aspect ratio from a video media type.

function SetPixelAspectRatio Helper function to set the pixel aspect ratio on a video media type.

function SetOutputRectangleAspectRatio Helper function to specify whether to pad a video image so that it fits within a specified aspect ratio.

function GetVideoDisplayArea Gets display area from a media type.

function CorrectAspectRatio Convert a rectangle from one pixel aspect ratio (PAR) to another, while preserving the picture aspect ratio.

function LetterBoxRect Calculates the letterbox area, given a source and destination rectangle. It is assumed that both rectangles have the same PAR.

Others

function GetMetadata Gets metadata from a media source or other object. If a media source supports this interface, it must expose the interface as a service. To get a pointer to this interface from a media source, call IMFGetService.GetService. The service identifier is MF_METADATA_PROVIDER_SERVICE. Other types of object can expose this interface through QueryInterface. Use this interface to get a pointer to the IMFMetadata interface.

function GetActiveStreamIndex Returns the stream identifier from an active stream, of a given streamtype.

function GetStreamContents Gets the streams information from a source (like language, format, compression etc.) It returns an array of the stream content values.

function GetMediaType Returns the Major guid and compression.

function IsMajorType Check if a given guid is a major type. Returns True or False.

function GetMediaDescription Returns the mediatype associated with the Major guid. To get the major type call function GetMediaType.

function GetMajorTypeDescr Returns the name of the Majortype constant. (RTTI will not work on some Delphi versions)

function GetAudioFormat Gets audio (EndPoint)device capabilities.

function GetAudioSubType Gets audio stream info from a media source (IMFMediaSource).

function GetWinAudioEncoderFormats Gets the Windows supported audio encoder formats (MFT's).

function AttributeGetString Helper function to get an attribute whose value is a string. For example: To get the MFT friendly name use MFT_FRIENDLY_NAME_Attribute. This is an overloaded function to use IMFAttributes or IMFActivate as in parameter.

Ducking

function SetDuckingForSystemSounds This function gets a reference to the IAudioSessionControl2 interface and call its methods to determine whether the stream associated with the audio session is a system sound.

Sami (.smi .sami)

Synchronized Accessible Media Interchange (SAMI) is a format for adding captions to digital media. The captions are stored in a separate text file with the file name extension .smi or .sami. In Media Foundation, SAMI caption files are supported through the SAMI media source. Use the Source Resolver to create an instance of the SAMI media source from a URL or byte stream. Media Foundation does not provide a component that displays SAMI captions. The application must interpret the caption data that it receives from the SAMI media source.

To change the current style, use the IMFSAMIStyle interface. This interface is obtained by calling IMFGetService.GetService on the SAMI media source. (If you are using the SAMI media source with the Media Session, call GetService on the Media Session.) The service identifier is MF_SAMI_SERVICE.

function SetSAMIStyleByIndex This function sets the current SAMI style, specified by an index.

Media files duration and filesize

function GetFileDuration Getting the File Duration. To get the duration of a media file, call the IMFSourceReader.GetPresentationAttribute method and request the MF_PD_DURATION attribute.

function GetFileSize Gets the file size.

External methods

function SetForegroundWindow Brings the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window, and various visual cues are changed for the user. The system assigns a slightly higher priority to the thread that created the foreground window than it does to other threads.

function LockSetForegroundWindow The foreground process can call function LockSetForegroundWindow to disable calls to function SetForegroundWindow.

Aliases section

CreateVideoCaptureDeviceBySymolicLink Renamed function and procedures for backward compatibility

Misc

procedure CopyWaveFormatEx Copies a WAVEFORMATEX structure to a WAVEFORMATEX structure pointer.

procedure GetSpeakersLayOut Get the assignment of audio channels to speaker positions and name, from a given MF_MT_AUDIO_CHANNEL_MASK attribute.